MVC 2
我试图使用jQuery发布到MVC操作,但我得到了一个异常,说明id为null。我是否需要控制器操作中的某种属性来接受这样的json数据包?还有我遗漏的东西吗?
[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
});
}在Chrome developer工具中,这是一个例外:
参数字典为'Current.Web.BackOffice.WebUI.Controllers.SiteProductAssociationsController'.中的方法'System.Web.Mvc.ActionResult SearchCategory(Int32,System.String,Int32,Int32)的非空类型'System.Int32‘的参数'id’包含一个空项。可选参数必须是引用类型、可空类型,或者声明为可选参数。参数名称:参数
编辑
以下是chrome发布数据的屏幕截图,我看不出有什么问题:

发布于 2012-03-20 18:22:51
修改post函数如下:
function post(targetURL, dataInput, success) {
$.ajax({
url: targetURL,
type: "POST",
data: dataInput,
success: success,
async: true
});
}MVC比asmx web服务更聪明。实际上,您可以传递一个普通的JavaScript对象,而不是坚持使用json字符串。有关详细信息,请参阅this answer。
当您以javascript对象的形式给jQuery的$.ajax()函数一个数据变量时,它实际上将它转换成一系列的键/值对,并以这种方式发送给服务器。当您发送字符串化的json对象时,它不是以这种形式出现的,mvc/mvc 2中的标准模型绑定器也不会对它进行剪切。
还请注意,异步参数是多余的,因为true是默认值,但这不会伤害任何东西。
https://stackoverflow.com/questions/9792600
复制相似问题