jQuery AJAX - 控制器上的数据参数为空

时间:2012-11-16 16:51:49

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

使用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
});

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

enter image description here

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

注意: JSON与POCO相同。

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

3 个答案:

答案 0 :(得分:3)

有时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));

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

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

答案 1 :(得分:1)

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

你必须为你的数据声明一个包装类,如下所示:

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

和您的控制人员:

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

修改    尝试使用quotations.eg({"theLicense": license }

围绕您的json对象的成员

答案 2 :(得分:0)

试试这个:

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
   }

   ...
}