jquery - ASP.NET MVC : Values sent by jQuery ajax is not being bound to the view model by the action

标签 jquery ajax asp.net-mvc

我无法解释为什么我发送到 Controller 的参数始终为空。这是我的 AJAX 调用:

var contactViewModel = { "CustCompId": _custCompId, "SuppID": 0 };

$.ajax({
         async: false,
         type: 'POST',
         data: JSON.stringify(contactViewModel),
         url: crudServiceBaseUrl + "GetContacts",
         success: function (result) {
                  contactData = result;
         }                           
  });

这是应该将参数发布到的操作

public JsonResult GetContacts(SuppOrCustViewModel contactViewModel)
{
   //CustCompId and SuppID are always null
}

这就是我定义 SuppOrCustViewModel

的方式
public class SuppOrCustViewModel
{
    public int? CustCompId { get; set; }
    public int? SuppID { get; set; }
}

当我在 GetContacts 中设置断点时,contactViewModel 中的两个属性都为 null。有什么理由吗?查看浏览器发送的内容,我看到的是: {"CustCompId":4,"SuppID":0}:

感谢您的帮助。

最佳答案

其实,我越想越觉得我之前的回答是错误的。所以我正在修改我的声明:

这很可能是由于缺少 ajax contentTypes 导致的问题。删除 stringify 会强制模型绑定(bind)器将其视为键/值对,并按预期工作。将其字符串化,而不设置正确的 contentType,会将整个对象视为键(没有值)。

我做了以下测试(在这里进行了全面测试)。

您如何发送它(没有 contentType 的情况):

$.ajax({
     async: false,
     type: 'POST',
     data: JSON.stringify(contactViewModel),
     url: "/echo/json/",
     success: function (result) {
         console.log(result);
     }                           
});

检查实际发送的内容时:

enter image description here

我第一次建议的方式(不刺激,即作为键/值对发送):

$.ajax({
     async: false,
     type: 'POST',
     data: contactViewModel,
     url: "/echo/json/",
     success: function (result) {
              console.log(result);
     }                           
});

这有效,并且 MVC 可以正确绑定(bind)它。检查实际发送的内容时:

enter image description here

最后,它可能应该如何发送(使用 contentType 进行字符串化):

$.ajax({
     async: false,
     type: 'POST',
     data: JSON.stringify(contactViewModel),
     url: "/echo/json/",
     dataType: 'json',
     contentType: 'application/json',
     success: function (result) {
              console.log(result);
     }                           
});

检查实际发送的内容时:

enter image description here

因此,将 contentType 与 stringify 结合使用非常重要。您的可为 null int 也有可能会导致问题(已知它会导致模型绑定(bind)出现问题),但我相信您能够解决这个问题。

关于jquery - ASP.NET MVC : Values sent by jQuery ajax is not being bound to the view model by the action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420990/

相关文章:

jquery - setInterval 在 jquery 中不起作用

jquery 动态背景图片 url 不起作用

javascript - 将表单操作作为整个 url 发送而不破坏

javascript - Backbone.js 默认路径(子域)

asp.net-mvc - 在 MVC 中读取和显示上传的文本文件

javascript - 如何在 Javascript 中打开下载对话框?

javascript - 使用循环打印javascript的时间

javascript - Yii Framework 2.0 检查是否是来自 AJAX 的 GET 请求

jquery - JsonResult 和 ajax.BeginForm 之间的区别

asp.net-mvc - Azure AD 登录后自动注销