JSON将null值传递给IE9中的MVC 4控制器

JSON pass null value to MVC 4 controller in IE9

本文关键字:中的 MVC 控制器 IE9 null 值传 JSON      更新时间:2023-09-26

我在将JSON数据发布到MVC 4控制器时遇到了一些问题
以下方法在Firefox中运行良好,但不幸在IE 9 中失败

JavaScript:

var newCustomer = {
    CustName: $("#CustName").val(),
    CustLocalName: $("#CustLocalName").val(),
    CustNumber: $("#CustNumber").val(),
    CountryID: $("#SelectCountry").val(),
    City: $("#City").val()
};
$.ajax({
     url: '@Url.Content("~/CustomerHeader/CreateCustomerHeader")',
     cache: false,
     type: "POST",
     dataType: "json",
     contentType: 'application/json; charset=utf-8',                     
     data: JSON.stringify(newCustomer),
     success: function (mydata) {
         $("#message").html("Success");
     },
     error: function () {
         $("#message").html("Save failed");
     }
});

这是我的控制器:

public JsonResult CreateCustomerHeader(CustomerHeader record)
{
    try
    {
        if (!ModelState.IsValid)    
        {
            return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct   it and try again." });
        }
        RepositoryHeader.Update(record);
        return Json(new { Result = "OK", Record = record});
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

public JsonResult CreateCustomerHeader(CustomerHeader **data**)中的"data"变量为NULL,但在使用FireFox时,它持有正确的值。

更新:尝试使用$.post 的新方法

function CreateNewCustomer(newCustomer) {
    $.post("/CustomerHeader/CreateCustomerHeader",
      newCustomer,
      function (response, status, jqxhr) {
          console.log(response.toString())
      });
}

根据您所展示的位,这是一个简化的变体,使用jQuery.post()可以更一致地工作(http://api.jquery.com/jQuery.post/):

var data = {
    CustName: $("#CustName").val(),
    CustLocalName: $("#CustLocalName").val(),
    CustNumber: $("#CustNumber").val(),
    CountryID: $("#SelectCountry").val(),
    City: $("#City").val()
};
$.post({
    '@Url.Action("CreateCustomerHeader", "CustomerHeader")',                  
    data,
    function(response, status, jqxhr){
        // do something with the response data
}).success(function () {
    $("#message").html("Success");
}).error(function () {
    $("#message").html("Save failed");
});

$.post()使用$.ajax作为基础,但将一些细节抽象掉。例如,$.post调用没有缓存,因此不需要设置cache状态(如果设置了,则会忽略设置)。使用一个简单的JavaScript对象,jQuery可以决定如何序列化POST变量;使用这种格式时,我很少遇到模型绑定器无法正确绑定到.NET类的问题。

response是您从控制器发回的任何内容;在您的案例中,是一个JSON对象。status是一个类似于successerror的简单文本值,jqxhr是一个jQuery XMLHttpRequest对象,可以使用它来获取有关请求的更多信息,但我很少发现需要它

首先,我想对@Tieson.T没有提供视图JavaScript部分的详细信息表示歉意。这个问题实际上是由ajax调用后发生的$("#addCustomerHeaderModal").mode("ide")引起的。

完整脚本:

try{ ..
    var newCustomer =
                {
                    CustName: $("#CustName").val(),
                    CustLocalName: $("#CustLocalName").val(),
                    CustNumber: $("#CustNumber").val(),
                    CountryID: $("#SelectCountry").val(),
                    City: $("#City").val()
                };

             $.ajax({                 
                 url: '/CustomerHeader/CreateCustomerHeader',
                 cache: false,
                 type: "POST",
                 dataType: "json",
                 data: JSON.stringify(newCustomer),
                 contentType: "application/json; charset=utf-8",                 
                 success: function (mydata) {
                     $("#message").html("Success");
                 },
                 error: function () {
                     $("#message").html("Save failed");
                 }
             });
             }
             catch(Error) {
                 console.log(Error.toString());
             }
             //$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!

我已经评论了$('#addCustomerHeaderModal').modal('hide'),现在控制器接收到的值在IE中不再是NULL。不知道为什么模式隐藏事件在IE9中会这样。

感谢大家为解决我的问题所做的一切努力,伙计们:-)