Making Asynchronous calls in ASP.Net MVC 3 - asp.net-mvc-3

I'm using $.ajax asynchronously to send some json to a controller marked with [HttpPost], like this:
$.ajax({
url: location.href,
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: theJson,
async: true,
});
This works fine, but the method expects an ActionResult, I guess with a new view. But I don't want that - I just want to do a little update on the server without updating the page.
Is there any way to set up a method on the server to do the update, independent of the view?

You should change the method to return void.

Related

How to send json in post body with jQuery mobile

Please help me, what is wrong in this code?
$.ajax({
type: 'POST',
url: baseUrl+url,
data: {language: 'it'},
xhrFields: {
withCredentials : true
}
})
why server receives:
'language=it_IT'
Try to specify your dataType and use JSON.stringify():
$.ajax({
type: 'POST',
url: baseUrl+url,
data: JSON.stringify ({language: 'it'}),
xhrFields: {
withCredentials : true
},
contentType: "application/json",
dataType: 'json'
})
I just run through the same issue: for some reason, whenever you send language parameter using ajax it somehow automatically changes to get and all post parameters get lost. Solution: avoid using language parameter at all (or stringify yout data as #Agash Thamo suggested. That is strange for me and I would really like if somoeno could explain that a little bit better.

Calling ASP.NET MVC 4 Controller from Javascript

I'm calling an ASP.NET MVC 4 control method from Javascript (in a cshtml file) using $.ajax() as shown below
$.ajax({
url: '#Url.Action("MyAction", "MyController")',
type: 'GET',
data: { 'id': "123"},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
}
});
The controller action method is
public JsonResult MyAction(string id)
{
// Do stuff
return new JsonResult();
}
which is getting called ok but is causing a GET 500 (Internal Server Error).
I don't really care about the returned data I just want to call the controller method to update a model.
Can anyone let me know why I'm getting the 500 or an alternative way of doing this that would be great.
For security reasons you cannot use the GET method in ajax requests (See JSON Hijacking).
You just have to do it like this:
return Json(data, JsonRequestBehavior.AllowGet)
or better off, change the method to post
type: 'POST',

Calling controller method (ASP MVC3) method from ajax doesn't work

I am using the following syntax to make a call to controller method from ASP page.
$.ajax({
url: 'ControllerName/MethodName',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify({ param: param1}),
success: function () {
alert("Success!!!");
},
error: function () {
alert("Failed!!!");
}
});
I have two ASP pages (views), both having same controller. If I call above method from first page, controller method gets called successfully. But if call same method from second page I get alert message "Failed". Also I tried using GET type, tried with other controller methods and all. Nothing will be called from second view. can anyone help me what can be problem? I am new to MVC.
Since your ajax is expecting result of JSON data from your Controller method do you have return Json(data, JsonRequestBehavior.AllowGet)?
Try change content type to:
contentType: 'application/json; charset=utf-8'
or/and specify url using mvc helper like:
url: #Url.Action("action"),
Works in my example. Hope it will help.

2 concurring ajax request one slow, one quick, both end in the same time

I have to query (via Ajax) 2 scripts at the same time.
I know for sure that one is really quick, it just displays some html, the second is doing some query using a WebService.
The quick request, is always sent after the first one. But with all my attempts, the fast/quick one, never completes before the slow one.
The code use to call the first long ajax request:
$.ajax({
type: "POST",
url: '/fr/ajax_flight_get_other_oneway',
cache: false,
dataType: 'json',
success: function(data) {
// some treatment
}
The code for the second faster ajax request:
$.ajax({
type: "POST",
url: '/fr/load_back_forflight?id=SN4422_23',
cache: false,
data: "comps="+compSelectedCodes+"&escale="+escale,
dataType: 'json',
success: function(data) {
// some treatment
}
Is it something in Apache that should be changed or is it in jQuery?
I found the solution to my problem, it was linked to the session.
the session was based on file system. So the first (long query) is lock the session file, and then the second one is forced to wait for the long query to finish.
by using session in DB, I've resolved the problem.
thanks for your help
Put the slow one in the success callback of the fast one. This will guarantee that the fast request will finish first before starting the second request.
It's possible that the browser decided to use the same HTTP connection for both (using the HTTP header Keep-alive) and thus it appears queued. This is not a jQuery thing -- it's something that browsers can opt to do.
Use your browser's HTTP network traffic debugger to see if that's the case.
If not, then your web-server may be only allowing one connection per client and is queueing them. See this:
How do I configure Apache2 to allow multiple simultaneous connections from same IP address?
Try this:
$.ajax({
type: "POST",
url: '/fr/ajax_flight_get_other_oneway',
cache: false,
dataType: 'json',
success: function(data) {
// some treatment
//The code for the second faster ajax request:
$.ajax({
type: "POST",
url: '/fr/load_back_forflight?id=SN4422_23',
cache: false,
data: "comps=" + compSelectedCodes + "&escale=" + escale,
dataType: 'json',
success: function(data) {
// some treatment
}
});
}
});​

Asp.Net Mvc 3, jQuery, cross-domain

I have a site "A" and to test cross site posts from site "B" using jQuery I've added this in Global.asax Application_BeginRequest
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST");
The post from site "B" looks like this:
$.ajax({
type: 'POST',
url: rootUrl,
crossDomain: true,
data: request.toPostData(),
dataType: 'json',
success: onsuccess,
error: onerror
});
My problem now is that it lets through two requests to the controller action. One with formvalues and one without.
Of course I only want the last one, which holds the values. I hope anyone could explain and point me to a solution.
to go across domains, you need to use something like jsonp http://en.wikipedia.org/wiki/JSONP
use dataType:'jsonp' and append your url with '&callback=?'
$.ajax({
type: 'POST',
dataType:'jsonp',
url: rootUrl,
crossDomain: true,
data: request.toPostData(),
success: onsuccess,
error: onerror
});
for more reference http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

Resources