Null value posting to MVC action with jQuery
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 post
function to this:
function post(targetURL, dataInput, success) {
$.ajax({
url: targetURL,
type: "POST",
data: dataInput,
success: success,
async: true
});
}
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.
When you give jQuery's $.ajax() function a data variable in the form of a javascript object, it actually translates it to a series of key/value pairs and sends it to the server in that manner. When you send the stringified json object, it's not in that form and the standard model binder in mvc/mvc2 won't cut it.
Also note that the async parameter is superfluous since true is the default value, but that won't hurt anything.
链接地址: http://www.djcxy.com/p/39222.html上一篇: 在Northwind DB中创建Controller Action CreateNewEmployee
下一篇: 使用jQuery将空值发布到MVC操作