Why i can not call action method with ajax? - 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.

Related

Unable to 'call' controller action from ajax post

I'm using net.core for the first time today and I'm trying to call an action method from an ajax call:
My Ajax call (from a normal HTML page)
$("#contactMap").click(function (e) {
e.preventDefault();
var url = "/MapObjects/mapContact";
//I've tried MapObjectsController & '#Url.Action("mapContact", 'MapObjects")'; But to no avail
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
And in my controller:
namespace myName.Controllers
{
public class MapObjectsController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult mapContact()
{
Account account = new Account();
return Json(account);
}
}
}
The 'account' is just a normal model (obvs empty in this case). All I receive is a 404 error in the console though.
As mentioned this is the 1st time I've .net Core (this is code I've written loads of times in 'normal' MVC projects) so it's possible that I'm missing something really obvious.
Thanks,
C
The first, try to call the #Url.Action() explicitly in the Ajax call :
$("#contactMap").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("mapContact", "MapObjects")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
The second, check your routing rules.

File deleted before downloaded in Ajax call in Asp.net MVC

I am generating a excel file by using the Ajax call to my Action in my controller class in my ASP.net MVC application.Its working fine but the problem occures some time when my file is in downloading stage and the ajax call delete it.If there is any way without SetTimeout then please tell me.
Generate Excel File
$.ajax({
url: "#Url.Action("GenerateReport", "ClientAdmin")",
type: "POST",
data: { reportStart: reportStart, reportEnd: reportEnd},
dataType: "json",
traditional: true,
success: function (downloadUrl) {
//Download excel file
window.location = "/ClientAdmin/Download?file=" + downloadUrl;
//Delete excel file
$.ajax({
url: "#Url.Action("DeleteReportFile", "ClientAdmin")",
type: "POST",
data: { file: downloadUrl },
dataType: "json",
success: function (downloadUrl) {
},
error: function () {
AlertShow("Error!", "Oops! An error occured");
}
})
},
error: function () {
AlertShow("Error!", "Oops! An error occured");
}
})
I think you need jQuery "when".
http://api.jquery.com/jQuery.when/
$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
alert( jqXHR.status ); // Alerts 200
});
this is to force something to be synchronous.
(One can find the credited answer here)
EDIT
as I am not sure how to test your case I might suggest another solution.
Try handling "file downloaded" event somehow and then trigger the delete function.
Here is a possible useful answer and blog.

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

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.

jQuery AJAX form how to get data

I have a form in my ASP.NET MVC 3 application that will use jquery to send it's data to the controller action instead of doing a normal postback:
$('.AjaxForm').live("submit", function (event) {
event.preventDefault();
$.validator.unobtrusive.parseDynamicContent('.uiModalContent input');
console.log($(this).attr('action'));
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: data,
success: function (responseHtml) {
alert(responseHtml);
},
error: function (responseHtml) {
alert('error');
},
statusCode:
{
404: function (responseHtml) {
alert('404');
},
500: function (responseHtml) {
alert('500');
}
}
});
});
However I get an error saying data is undefined... How do I get the data from the form and send it? Also does the built-in validation in ASP.NET MVC 3 work with my code or will I have issues? Thanks
You should use form.serialize() to make data value. Your code should be changed to:
url: $(this).attr('action'),
data: $('.AjaxForm').serialize(),
you can use the serialize or serializeArray method with form to pass all parameters with the ajax call.
data: $('.AjaxForm').serialize(),
http://api.jquery.com/serialize/
http://api.jquery.com/serializeArray/

Resources