Unable to 'call' controller action from ajax post - ajax

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.

Related

Razor Pages PageModel binding for GET with AJAX

I am having trouble getting binding to work with a specific set of circumstances. I am using Razor Pages with ASP.NET Core 3.1 to act like a controller for servicing AJAX calls. I have already added the anti-forgery token to the Startup.cs:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
My AJAX calls include the anti-forgery in the calls and look like:
function getTankConfig(tankId) {
var json = { id: tankId };
$.ajax({
cache: false,
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/Tank/Config",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(json),
success: getTankConfigSuccess
});
}
function getTankConfigSuccess(data) {
if (data !== null) {
// do stuff with data
}
}
I have tried about every combination of binding technique. Using the parameter normally, adding [FromBody], adding a public property and giving it the [BindProperty] attribute, using [BindProperty(SupportsGet = true)]. It seems like it was so simple when using a controller to do this, but I am not finding the magic for making it work with Razor Pages and PageModels.
Here is the simplified version of my PageModel class:
public class TankConfigModel : PageModel
{
public JsonResult OnGet(int id)
{
TankConfigViewModel config = new TankConfigViewModel();
config.Id = id;
return new JsonResult(config);
}
}
Any help or guidance would be greatly appreciated. Thanks.
You have to add this to your razor page
#page "{id}"
and fix ajax
$.ajax({
type: "GET",
url: "/Tank/Config/"+tankId,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (result) {
getTankConfigSuccess(result)
},
error: function (jqXHR) {
}
});

Passing multiple ajax parameters to mvc controller

I can pass a serialized form to a mvc controller no problems with code below and all is populated
$("#btnExecuteJob").on("click", function (e) {
var frmForm1 = $("#form1").serialize();
$.ajax({
cache: false,
url: "/mvcController/executeJob",
dataType: 'json',
type: 'POST',
data: frmForm1,
success: function (resp) {},
error: function (resp) {}
});
});
Controller
[HttpPost]
public ActionResult executeJob(runDetails jobDetails)
{
//
// Process
//
return View();
}
I have added a second form to my view and now want to pass both to the controller so I tried
$("#btnExecuteJob").on("click", function (e) {
var frmForm1 = $("#form1").serialize();
var frmForm2 = $("#form2").serialize();
$.ajax({
cache: false,
url: "/jobScheduler/executeJob",
dataType: 'json',
type: 'POST',
data: {
jobDetails: frmForm1,
jobParameters: frmForm2
},
success: function (resp) {},
error: function (resp) {}
});
});
Controller
public ActionResult executeJob(runDetails jobDetails, runParams jobParameters)
{
//
// Process
//
return View();
}
and neither jobDetails or jobParams is populated, both work individually as first example
and all details are populated, any help much appreciated,
both forms really need to be separate in the controller

Ajax and ASP.NET MVC- Get page URL, not the controller/action URL

I have an Ajax method that calls an MVC action from a controller class.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/ajax/Updates/Message",
dataType: "json",
success: function (response) {
//data variable has been declared already
data = response;
},
complete: function () {
if (data !== "") {
$('#div1').text(window.location.path);
$('#div2').text(data);
}
},
});
[HttpGet]
public async Task < ActionResult > Message()
{
string d = "test string";
return Json(d, JsonRequestBehavior.AllowGet);
}
The 'url' within the Ajax method is the call to the action method.
What to do if I want to return the actual page URL in Ajax Response, not the controller/action url?
So this controller does not have a view or anything associated with it, it is more like a helper class. When I am using ajax in any of the other pages, it is not returning the URL path of that specific page (via 'window.location.path) e.g. /Accounts/Summary , rather it is returning Updates/Message (in reference to the controller and action)
The web is stateless, when you call Updates/Message with ajax, it doesn't know it's for page Accounts/Summary. You'll have to pass this as parameter (post or get) or you could try Request.UrlReferrer which should contain the url of the page that called the request.
I hope this will help you try this code:
ajax code
$.ajax({
type: 'GET',
url: '#Url.action("Message","Updates")', // url.action(ActionName,ControllerName)
success: function (data) {
window.location = data;
},
error: function (xhr) { // if error occured
alert("Error occured.please try again");
}
dataType: 'json'
});
actionresult :
[HttpGet]
public async Task<ActionResult> Message()
{
string d = "http://www.google.com";
return Json(d, JsonRequestBehavior.AllowGet);
}

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.

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources