Calling ASP.NET MVC 4 Controller from Javascript - ajax

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',

Related

Ajax sending variable value to MVC controller

I am trying to send a value from jQuery using ajax call and fetch the value in the controller. Below is what I am trying, but the value of A is always null. Can someone help me where I am going wrong.
$.ajax({
type: "POST", //The type of Method being used (GET, SET, POST, etc.)
url: '/Controller1/Index',
contentType: 'application/json; charset=utf-8',
data: { A: "true" }, //Your data to pass to your Controller action
dataType: "json",
success: function (result) {
alert(response.responseText);
alert("Done!");
}
});
C# code
[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost(FilterRule queryBuilder, BootstrapTableQueryType bootstrapTable, string A)
{
string B = A;
}

Why i can not call action method with ajax?

I'm new in asp.net mvc want to call action method in the view page,for that purpose write this ajax code:
$('#SaveBTN').click(function (e) {
$.ajax({
url: "/Home/SaveRecord",
type: "POST",
data:'', //JSON.stringify({ 'Options': someData }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Done");
},
error: function () {
alert("An error has occured!!!");
}
});
});
this is my button:
ثبت نام
and this is my action:
[HttpPost]
public ActionResult SaveRecord()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
but when run the web application and fire button,get error segment alert in ajax ,How can i solve that problem?thanks all.
With the question and code presented in the way it is there is no way to help. I recommend starting from ground zero and stepping through this tutorial.
Basically that^ link will get you through the basics of using web api in MVC to do AJAX calls and populate the page. There are some other methods however this is the best place for trying to learn what you're studying.

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.

Unexpected GET request after POST on AJAX call to MVC Action

I have an action method that is invoked with POST method over AJAX. Method looks like this:
[HttpPost]
public ActionResult Save(MyModel model)
{
/// do something and save
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
What happens is that after this method is call by the $.ajax, from unknown reason follow up GET request is made to same controller and same action. This call is not made anywhere and it's probably implemented either in browser or in ASP.NET MVC as Post/Redirect/Get pattern which I don't need in this case.
Is there a way to disable this programmatically because GET counterpart of Save method is not implemented and server returns 404 with HTML contents in it.
EDIT, this is the client-side AJAX script:
function saveDonkey(donkey) {
var jsonData = JSON.stringify(donkey);
$.ajax({
url: "/Donkey/Save",
data: jsonData,
contentType: "application/json",
dataType: "json",
type: "POST",
success: function () {
fetchPage(); /// This just issues GET request to another predefined method
}
});
}

Jquery ajax returning null values back to controller - MVC3

I'm using jQuery ajax to build a viewmodel list and then trying to send that viewmodel to another ActionResult in order to create PartialViews. The first part works well, and I'm able to create the viewmodel (List), but when I try to send the viewmodel back to the controller to build up the partial views, everything within the viewmodel is 0. It returns the correct number of items in the list, but it seems to lose the values.
Can anyone see if I'm missing anything here?
jQuery:
$.ajax({
async: false,
type: 'GET',
dataType: "json",
url: '#Url.Action("GetMapDetails")',
success: function (data) {
$.ajax({
async: false,
type: 'POST',
dataType: "json",
url: '#Url.Action("GetMapItems")',
data: {
list: data
},
success: function (list) {
//callback
});
}
});
}
});
and the controller:
public ActionResult GetMapDetails()
{
List<ViewModel> vm = new List<ViewModel>();
//create viewmodel here
return Json(vm.ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult GetMapItems(List<ViewModel> list)
{
return PartialView("_MapItemsPartial", list);
}
I've tried also using contentType: 'application/json' and JSON.stringify(data) but that gave me an Invalid JSON primitive error.
Any help appreciated - thanks
You could send them as JSON request:
$.ajax({
async: false,
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("GetMapItems")',
data: JSON.stringify({
list: data
}),
success: function (result) {
//callback
}
});
Also notice that I have removed the dataType: 'json' parameter because your GetMapItems POST controller action doesn't return any JSON. It returns a PartialView. So I guess you did something wrong and this is not what it was meant to be returned from this controller action because from what I can see in your success callback you are expecting to manipulate JSON.
Oh, and please remove this async:false => it defeats the whole purpose of AJAX as you are no longer doing any AJAX, you are now doing SJAX.

Resources