MVC 2
I’m trying to post to an MVC action using jQuery, but I’m getting an exception stating that id is null. Do I need some sort of attribute on the controller action to accept json packets like this? Something else I’m missing?
[HttpPost]
public ActionResult SearchCategory(int id, string SearchTerm, int PageNumber, int SiteIdFilter)
{
return Json(AssociationsDao.SearchCategory(id, SearchTerm, PageNumber, SiteIdFilter));
}
post('<%= Url.Action("SearchCategory") %>',
JSON.stringify({id: 12, SearchTerm: '', PageNumber: 1, SiteIdFilter: 1}),
function(d) { alert(d); });
function post(targetURL, dataInput, success) {
$.ajax({
url: targetURL,
type: "POST",
contentType: "application/json; charset=utf-8",
data: dataInput,
dataType: "json",
success: success,
async: true
});
}
From the Chrome developer tools, this is the exception:
The parameters dictionary contains a null entry for parameter ‘id’ of
non-nullable type ‘System.Int32’ for method
‘System.Web.Mvc.ActionResult SearchCategory(Int32, System.String,
Int32, Int32)’ in
‘Current.Web.BackOffice.WebUI.Controllers.SiteProductAssociationsController’.
An optional parameter must be a reference type, a nullable type, or be
declared as an optional parameter. Parameter name: parameters
EDIT
Here’s a screenshot of the post data from chrome; I can’t see anything wrong with it:

Modify the
postfunction to this:MVC is smarter than asmx web services. Instead of insisting on a json string, you can, in fact need to, just pass a plain JavaScript object. See this answer for more information.
Also note that the async parameter is superfluous since true is the default value, but that won’t hurt anything.