c# - 使用 jQuery 将空值发布到 MVC 操作

标签 c# asp.net-mvc asp.net-mvc-2

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 的帖子数据的屏幕截图;我看不出有什么问题:

enter image description here

最佳答案

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/

相关文章:

c# - 为什么 ApiController 在方法上需要显式的 Http 动词?

c# - 使用 MVC4 asp.net 随机注销

asp.net-mvc-2 - Asp.net Mvc String的显示模板,但是现在每个简单类型都想用它!

ASP.NET MVC2 将无法工作。出现 "The resource cannot be found."错误

c# - 在基于网格的游戏中放置墙壁/道路

c# - C#中如何计算字符串中的段落数

c# - 编码(marshal)结构数组和 IntPtr

asp.net-mvc - 如何在 ASP.NET MVC 中构造 moSTLy 静态页面

asp.net-mvc - ASP.NET MVC : Response. Redirect(url, TRUE) 不会停止请求处理

asp.net - 将 View 模型从 ajax 发送到 Controller