How to open a window using Javascript from ASP.NET MVC? - javascript

I am writing a tiny MVC app that is a utility to simulate the actions of getting an id from a portal and setting it in a database for another app to obtain while this app is open. I attempted to write it using ASP.NET MVC to "get my feet wet." In it, I am attempting to use the JavaScriptResult (DESPITE all the warnings) to execute Javascript's window.open function but I get only a file dialog that is acting like the FilePathResult - it displays a dialog box asking if I want to save my file which is the name of the ActionEResult. How do I do this?
public JavaScriptResult SessionTransferDesktop(string PortalUserId)
{
/// .... Call Oracle SP to set token
// Redirect to RON Scheduler
string js = "window.open('/RONSchedulerMVC/default.aspx?p_token=' + portalToken);";
// string js ="window.open('http://microsoft.com')";
return JavaScript(js);
}

public ActionResult SessionTransferDesktop(string PortalUserId)
{
/// .... Call Oracle SP to set token
// build url and redirect
var uriBuilder = new UriBuilder("http://example.com");
uriBuilder.Path = "/RONSchedulerMVC/default.aspx";
uriBuilder.Query = "p_token=" + Url.Encode(portalToken);
return Redirect(uriBuilder.ToString());
}

You are getting the file result because your browser is requesting something and getting content-type:application/javascript back.
The easiest way to get this to work is to simply make the route redirect the response to the portal. You can then just call window.open directly on said route and profit.

Related

Calling jersey client by button click

I have a jersey client class which is making a put request to a rest.
//JerseyClient
public void putRequest() throws Exception{
reloadUri();
Response response = target.request(MediaType.APPLICATION_JSON)
.accept("application/json;charset=UTF-8")
.header("Content-Type", "application/json")
.header("Authorization", "Basic OTA1MzAwNjY3MDg2OjZ4dDg5dk50VXdCbg==")
.put(Entity.entity(sub, MediaType.APPLICATION_JSON),Response.class);
System.out.println(response);
if(response.getStatus() == 200) {
System.out.println("put request using Json is Success");
}
}
It's working fine, but I wanted to call this function with a button click. And this button is placed on one of my jsp file. So, is there a way to call this request inside that jsp file when button clicked.And redirect the page into new jsp according to response of rest.
No directly by the jsp. If you include this code in the jsp, it will be executed while parsing the jsp page in the server.
You should include it in a Java component which will be called by a Servlet (or controller, filter, etc...). The button in your jsp will make a call to the URL which executes that component, and is there where you must do whatever you need with the result.
If you want to execute directly in the jsp while clicking the button, you must make it using javascript in client side.
You may call this method using URL reference:
define a path annotation for method:
#Path("/PATH")
#GET// or #POST
public void putRequest() throws Exception{
...
}
And then, from you jsp page you can define the button to redirect to this URL to initiate the above method.
You may read more about jersey annotations here.

Change content of file - Alfresco

I have an Custom Document Library Action to Alfresco files, and when I press this button opens a new page with an applet (javascript) to make changes to a file, but I'm doing the modifications in base64 and to "appear" on the screen with this :
var stringPDF = "<object data=\"data:application/pdf;base64," +
JSON.parse(pdfbase64).message + "\"
type=\"application/pdf\"width=\"100%\"
height=\"100%\"></object>";$("#pdfTexto").html(stringPDF);
But I really need is to change the file, for when the repository again, there have to change, not just display. How do I change the existing file's contents to the new with the change?
I use this URL to make GET of the file:
http://localhost:8080/share/proxy/alfresco/slingshot/node/content/workspace/SpacesStore/21384098-19dc-4d3f-bcc1-9fdc647c05dc/latexexemplo.pdf
Then I convert to the base64... And I make the changes...
But if I want to make a POST to change the content, how can I make this?
Thanks in advance.
As I mentionned in my response to this question :
The fastest and easiest way to achieve that is to leverage the RESTfull API
This will also ensure compatibility with new versions of alfresco.
Note that you need to provide the noderef for the document to update in the form property updatenoderef and that the property majorversion is a boolean flag to specify if the new version is a minor/major version of the document.
Here is a sample code that might help you with your usecase:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(<alfresco-service-uri>+"/api/upload?alf_ticket="+<al-ticket>);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", "<username>", ContentType.TEXT_PLAIN);
builder.addTextBody("updatenoderef", <noderef>, ContentType.TEXT_PLAIN);
builder.addTextBody("...", "...", ContentType.TEXT_PLAIN);
builder.addBinaryBody("filedata", <InputStream>, ContentType.DEFAULT_BINARY, <filename>);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
JSONObject responseJson = new JSONObject(responseString);
if (response.getStatusLine().getStatusCode()!=200){
throw new Exception("Couldn't upload file to the repository, webscript response :" + responseString );
}
Note 1: You need to replace these tockens <*> with your own values/vars
Note 2: If you have problem retrieving a ticket, check this link, or this one
Note 3: To do this in JavaScript instead of java, visit this link and try to use js to post the parameters I referred as instructed !
Note 4: Since you are working on share, you are most probably authenticated.
If it is the case, you can access your alfresco repo through the proxy endpoint in share and all requests will have authentication ticket attached to them before getting forwarded to your repo !
In other terms, use this endpoint :
/share/proxy/alfresco/api/upload
Instead of :
/alfresco/service/api/upload
and You won't even have to attach a ticket to your requests.
You need to follow these steps to achieve what you are looking for.
1) Reading File:
To display content of PDF file already uploaded you need to read content of file. You are able to do it successfully using following API call.
http://localhost:8080/share/proxy/alfresco/slingshot/node/content/workspace/SpacesStore/21384098-19dc-4d3f-bcc1-9fdc647c05dc/latexexemplo.pdf
2) Capture New Content:
Capture new file content from User from applet. I guess you are storing it in some String variable.
3) Edit Existing File Content:
Issue here is that you cannot simply edit any pdf file using any of out of box Alfresco REST API (as far as I know). So you need to create your own RESTFul API which could edit pdf file's content. You can consider using some third party libraries to do this job. You need to plugin logic of editing pdf in RESTFul API
4) Changes back to Repo:
Call Your API from Step 3:
You could also have look at this plugins which could fulfill your requirements.
https://addons.alfresco.com/addons/alfresco-pdf-toolkit
Hope this helps.

Call Sitecore controller method from JavaScript (MVC)

I have a controller with a function ShowEvents(EventCategory eventCategory). Is it possible to call this function from client-side JavaScript? I know that I can retrieve items from the database using the Sitecore.Services.Client (SCC), but is it possible to actually access methods? Maybe through the controller rendering, if that's possible?
Here is an example of a method I want to call:
public class EventListController : Controller
{
public ActionResult ShowEvents(EventCategory eventCategory)
{
var repository = new EventListRepository();
var eventPages = repository.GetEvents(eventCategory);
var eventListViewModel = repository.GetEventListViewModel(eventPages);
return View("/Some/Path/, eventListViewModel);
}
}
This is on Sitecore 7.5 MVC
You can Post to controllers from the client side using the format
/api/sitecore/{yourcontroller}/{action} in your case this would be /api/sitecore/eventlist/showevents passing the eventCategory as the data.
yes you can reach every function with
A separate view page named with same name of it and the view pages
will be written with RAZOR language which is composed of c# and html
and surely you can write javascript within the html code.
with the Asp.net and MVC5
here an example :::
http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started
You can use the below format for call the Action method in sitecore project.
Sitecore have own route to manage the action method which is used as API. You can use it for Ajax call from the fronted.
/api/Sitecore/{controller Name}/{action method name}
Just post your data as request in data object and cosume the url in above format. It's act like API.

cannot connect to Web API

I am new to WebAPI programming .Here is what have I done
Created ASP.NET web Application SampleWebApiProject in Visual Studio 2013
under .NET Framework 4.5.2
Selected MVC and checked Web API under [Add Folders and core references for].
using Nuget package installed knockout.js ,knockout-validation.js etc etc.
In my code for Login.cshtml I have html button
<div>
<button type="button" class="btn btn-info" data-bind="click:$parent.login">
Login
</button>
</div>
And on my click button I have
self.viewModelHelper.apiPost('api/account/login', unmappedModel,
function (result) {
}
And I have created API Controller called AccountApiController
public class AccountApiController : ApiController
{
[HttpPost]
[POST("api/account/login")]
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]AccountLoginModel accountModel)
{
return null;
}
}
However when I inspect the click event in Chrome developer tools I get an error response
POST http://localhost:64436/api/account/login 404 (Not Found).
this is my WebApiConfig
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Am I working with right type of application ?
Screenshot
Try:
self.viewModelHelper.apiPost('api/accountapi/login', unmappedModel,
function (result) {
}
and API Controller
public class AccountApiController : ApiController
{
[HttpPost]
[POST("api/accountapi/login")]
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]AccountLoginModel accountModel)
{
return null;
}
}
Your account controller is named accountapi and not account, so webapi can't find any controller called account.
I'm not sure, but your parameters look wrong in your webapi controller...
Why would you add HttpRequestMessage as a parameter?
You have called your controller AccountApiController and so api/account/login should be accountapi/login
Web API has a strict calls when it comes to MVC architecture.
If you call POST. It means that the API will really CREATE a new Entity, and Does NOT, make other request to be returned.
So meaning, the WebAPI is not custom API function Call that you thought it might be.
It is different from creating an individual API to Creating an web API inside an MVC Application.
Here is are some Notes.
GET : Retrieve an entity
PUT : update an entity
POST : create a new entity
DELETE : remove an existing entity.
so let us say you have an API for Account Models. I will say Models cause when creating an Web API. You need a Model. Unless you're creating your custom API. Outside the MVC.
Now you did this. api/account/test
What it will do is use the [GET] function.
Whatever function you have in the account controllers that have a Data Annotation of [GET] will be executed. And return you something.
And No. Don't use Login as the name of the Method just use GET as you can't really tell the Web API which function to use. It WILL use the one with the GET data annotation. So entering
api/account/ login <---- this will not call the login method, it is entering a string data to be passed to the Get Method.
[HttpGet]
public IEnumerable<string> Get()
{
return "No Value";
}
[HttpGet("{id}")]
public IEnumerable<string> Get(int id)
{
return "There is a value";
}
Now if you want the POST to be Called. Simply create a A Form that has a method of POST. Or JQuery Javascript and call generate the POST method for them. You can't write the Method call in the address bar. You just have to use the right kind of request to call the specific function or function with overload.

asp.net mvc url action in javascript code and IIS publish

I am developing asp.net mvc project. I have a javascript object that sends query to controller action. in cshtml file I can use #Url.Action("get", "product") so when I publish the web site, url action is rendering by location url. If I publish it http://localhost/App1/, the action url is like this http://localhost/App1/product/get or I can publish it another directory like http://localhost/App2/ and so on.
But I have an issue in javascript code.
sample.js
function query(){
var url = "/product/get";
// send query this url
}
When I publish the project in http://localhost/App1/ url (APP1 folder), javascript query is sending request to http://localhost/product/get , but it should be like this http://localhost/App1/product/get
I can not use #Url.action() razor expression. How can I solve this issue?
You can place root level appPath variable in your _layout.cshtml
<script type="text/javascript">
var appPath = #Url.Content("~/");
</script>
Then in your query
function query(){
var url = appPath +"/product/get";
}
I send the url as a parameter from the View to the javascript function which is written in a js file. This saves you the trouble of creating a url in js and you can use you razor expression for the same.
So your function becomes:-
function query(url){
//var url = "/product/get";
// send query this url
}

Categories