I have been digging around for a few hours now and just not finding anything. A lot of questions similar to this are about posting to controllers but I am just trying to post a single integer. I have confirmed the code is calling into the controller as I can hit a break-point in the controller and see that the value I have hard-coded is not being passed to the controller. I am sure there is something stupid I am missing but I can't figure it out after trying a lot of different things the controller always get the value of "0" for the selectedNavigationItemID
. What am I missing to pass the integer into my controller?
Striped out AJAX call:
$(document).ready(function()
{
$('#SelectedExistingNavigationItemID').change(function()
{
$.ajax('../Sections/GetSectionNavigationItemInfo/'),
{
type: 'POST',
dataType: 'json',
data: { 'selectedNavigationItemID': '3'},
success: function(data, status, jqXHR)
{
if ("success" == status)
{
alert('good');
}
}
};
});
});
Code on my controller side:
[Route("GetSectionNavigationItemInfo")]
public async Task<JsonResult> GetSectionNavigationItemInfo(int selectedNavigationItemID)
{
var navigationItem = await _navigationHelper.GetSectionNavigationMenuItem(selectedNavigationItemID);
return Json(navigationItem);
}
I have tried removing the questions around the information in data
, specifiying application/json
for a contentType
, changing dataType
to multipart/form-data
but it all results in the value of 0
being passed into the controller.
What stupid little thing am I missing to make this work?
CodePudding user response:
If you look at the browser's network tab, it's probably being sent with the GET
method, because your ajax
syntax is incorrect and Ajax Configuration aren't applied, and by default it's being sent with the GET
method, try changing your code to :
$(document).ready(function()
{
$('#SelectedExistingNavigationItemID').change(function() {
$.ajax({
url: '../Sections/GetSectionNavigationItemInfo/',
type: 'POST',
dataType: 'json',
data: { 'selectedNavigationItemID': '3' },
success: function(data, status, jqXHR) {
if ("success" == status) {
alert('good');
}
}
});
});
});
A tip to improve your code:
It is better to add [HttpPost]
attribute to your action so that your action is only available via POST
method. This way, your action method would no longer be called with the GET
method, and you could debug your code more easily and find the problem.
[HttpPost]
[Route("GetSectionNavigationItemInfo")]
public async Task<JsonResult> GetSectionNavigationItemInfo(int selectedNavigationItemID)
{
var navigationItem = await _navigationHelper.GetSectionNavigationMenuItem(selectedNavigationItemID);
return Json(navigationItem);
}