MVC 2
我正在尝试使用 jQuery 发布到 MVC 操作,但出现异常,指出 id
为 null。我是否需要 Controller 操作上的某种属性来接受这样的 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 开发者工具来看,这是一个异常(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
编辑
这是来自 chrome 的帖子数据的屏幕截图;我看不出有什么问题:
最佳答案
将 post
函数修改为:
function post(targetURL, dataInput, success) {
$.ajax({
url: targetURL,
type: "POST",
data: dataInput,
success: success,
async: true
});
}
MVC 比 asmx Web 服务更智能。事实上,您可以只传递一个普通的 JavaScript 对象,而不是坚持使用 json 字符串。请参阅this answer了解更多信息。
<小时/>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.
另请注意,async 参数是多余的,因为 true 是默认值,但这不会造成任何损害。
关于c# - 使用 jQuery 将空值发布到 MVC 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9792600/