使用MVC3进行JSON序列化

时间:2011-12-07 22:14:03

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

如何将以下序列化为json结果?该对象将以null返回给我的控制器。

public class CertRollupViewModel
{
    public IEnumerable<CertRollup> CertRollups { get; set; }
}

public class CertRollup
{
    public decimal TotalCpm { get; set; }
    public decimal TotalIO { get; set; }
}

// The json obj leaves the controller method "GetAlerts" ok but not sure how to validate if the object
//   is intact before it get's passed into the GetCertRollupView.
//   The GetCertRollupView is where the json object is null

// Some button click...
$.get('@Url.Action("GetCerts")',   **// STEP 1**
    function (data) {
     $("#rollupgridview").load('@Url.Action("GetCertRollUpView")',  **// STEP 3**
        data);
...

public ActionResult GetCerts()  **// STEP 2**
{
    ...
    return Json(CertRollupViewModelObject, JsonRequestBehavior.AllowGet);
}

public ActionResult GetCertRollUpView(CertRollupViewModel certRollupViewModel)  **// STEP 4**
{
  // certRollupViewModel IS NULL!!!
 return PartialView("_CertRollUp", certRollupViewModel);
}

注意:结构确实正确传递,但CertRollup的值为0。

每个Visual Studio的立即窗口:

?certRollupViewModel.CertRollups 
     Count = 1
    [0]: {Models.CertRollup} ?CertRollupViewModel.CertRollups.First() {Models.CertRollup}
    TotalCpm: 0

3 个答案:

答案 0 :(得分:1)

试试这个:

function loadRollupGridView () {
    $.ajax({
        url: '@Url.Action("GetCerts")',
        type: 'GET',
        success: function(certRollupViewModel) { 
            $('#rollupgridview')
                .load('@Url.Action("GetCertRollupView"), certRollupViewModel)');
        },               
        error: function () {
            $('#rollupgridview')
                .html('<div class="error">Something went wrong...</div>');
        }
    });
}

我认为主要问题是您将变量data传递给Controller,而不是像预期的那样certRollupViewModel

这是您的JSON对象传递给控制器​​时的样子:

{"certRollupViewModel": 
  {"CertRollups":
    [
      {"TotalCpm": "25.35", "TotalIO": "380.23"}, 
      {"TotalCpm": "25.35", "TotalIO": "380.23"},
      {"TotalCpm": "25.35", "TotalIO": "380.23"}
    ]
  }
}

答案 1 :(得分:0)

JsonResult ActionRoutine()
{
   ...
   return Json( data );
}

更新:我认为你正在考虑将JSON返回给一个动作方法。我已经取得了成功,将带有args的参数与JSON参数作为方法签名。

答案 2 :(得分:0)

也许我错过了将序列化数据发送到哪里? 查看表单的序列化方式

Serializing form data doesn't work in asp.net mvc app

在上面的代码中,我没有看到您指定要发送到控制器的数据