【问题标题】:jQuery AJAX - data parameter blank at controllerjQuery AJAX - 控制器的数据参数空白
【发布时间】:2012-11-16 16:51:48
【问题描述】:

使用ASP.NET MVC 3,我正在做一个jQuery (ver 1.7.1) AJAX 调用,就像我做了十亿次一样。但是,我注意到了一些奇怪的事情。 以下调用工作正常

// license object
var license = {
    City: "New York",
    CompanyID: 1,
    County: "N/A",
    IsActive: true
};
// make the request
var $req = $.post('/License/theLicense', license); 
$req.success(function () {
    // this works!
});


[HttpPost]
public void Save(License theLicense)
{
    // save
}

但是,当我为控制器指定数据参数时,它不会在控制器上注册

// license object
var license = {
    City: "New York",
    CompanyID: 1,
    County: "N/A",
    IsActive: true
};
// make the request
// this time the controller parameter is specified
// the object will be blank at the server
var $req = $.post('/License/theLicense', { theLicense: license });
$req.success(function () {
    // this does not work
});

控制器上的对象是空白的,如下图所示

这很烦人,因为我需要传递另一个数据参数,但由于这个问题我不能。

注意: JSON 与 POCO 相同。

为什么当我指定数据参数时,对象在控制器上显示为空白,但当我不指定时它就没事了?

【问题讨论】:

  • 投反对票的人真的可以评论他们投反对票的原因吗?这有点荒谬。我花了很多时间提出这个问题。

标签: jquery asp.net asp.net-mvc asp.net-mvc-3


【解决方案1】:

有时 POCO 反序列化器会因为奇怪的原因而受到影响。我以前见过我的 JSON 对象与 POCO 完全匹配的地方,但它仍然不会反序列化。

发生这种情况时,我通常将对象作为 JSON 字符串发送到服务器,然后在服务器上对其进行反序列化。我个人使用 ServiceStack.Text,因为它是最快的。

所以你的 jQuery 会变成这样:

var license = {
    City: "New York",
    CompanyID: 1,
    County: "N/A",
    IsActive: true
};

var $req = $.post('/License/theLicense', JSON.stringify(license));

然后你的控制器会接受一个字符串参数(json)来反序列化对象:

   [HttpPost]
   public void Save(string json)
   {
       License theLicense = JsonSerializer<License>.DeserializeJsonString(json);
       // save
   }

【讨论】:

    【解决方案2】:

    发生这种情况是因为您正在发送一个包含许可证的对象作为成员,但您的控制器需要一个 License 对象。

    您必须像这样为您的数据声明一个包装类:

      public Class MyWrapperClass
      {
          public License theLicense;
          //declare other extra properties here  
      }
    

    和你的控制器:

    [HttpPost]
    public void Save(MyWrapperClass thewrraper)
    {
        var license = thewrapper.theLicense;
        // save
    }
    

    编辑: 尝试用引号包围你的 json 对象的成员。例如({"theLicense": license }

    【讨论】:

    • 我喜欢这个解决方案,但我的许可类在包装类中仍然是空白的。
    • 你确定json和POCO一模一样吗?
    • 将 FormCollection 作为参数放入控制器操作中并检查是否来自客户端的数据正确?
    【解决方案3】:

    试试这个:

    JS:

    // license object
    var license = {
        City: "New York",
        CompanyID: 1,
        County: "N/A",
        IsActive: true
    };
    
    var $req = $.post('/License/Save', { theLicense: license });
    $req.success(function () {
        // this does not work
    });
    

    .NET

    public class LicenseController: Controller 
    {
       ...
    
       [HttpPost]
       public void Save(License theLicense)
       {
           // save
       }
    
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      相关资源
      最近更新 更多