MVC3 - 将Json模型传递给控制器​​(字典)

时间:2013-12-16 16:44:27

标签: javascript ajax json asp.net-mvc-3 dictionary

当我从ajax调用中收到Json数据时,我的模型为null:

这是我在C#中的模型:

public class ErrorReportModel
{
    public bool isSuccess { get; set; }
    public Dictionary<string, ScriptExecResultEntity[]> Errors{get;set;}
}

这是我的ajax电话:

   StringJsonLastExecutionReportModel = JSON.stringify(JsonLastExecutionReportModel);
   $.ajax({
    url: urlPath,
    type: 'POST',
    dataType: 'html',
    data: StringJsonLastExecutionReportModel,
    contentType: 'application/json; charset=utf-8',
    success: function (data, status, xhr) {

    },
    error: function (xhr, status, error) {
        alert(error);
    }
   });

Json数据(StringJsonLastExecutionReportModel)看起来像这样,它有效:

{
    "isSuccess": false,
    "Errors": {
        "e794bfa7-657b-482c-acdf-c5a3b6d2ce83": [
            {
                "ErrorMsg": "Invalid object name 'asfasf.CONTACT'.",
                "Id": "63755f2a-1f02-480e-ab94-cafc62fd9634",
                "ScriptContent": "CREATE VIEW [asfasf].Blala AS select * from [asfasf].[CONTACT]",
                "ScriptDescription": "Script 6",
                "ServerType": "SQLSERVER",
                "Success": false
            }
        ]
    }
}

这是我的控制器方法:

    public void DisplayErrorsReportAsync(ErrorReportModel model)
    {
        AsyncManager.Parameters["ErrorReportModelObject"] = model;
    }

收到的模型如下所示:

Received Model

为什么我的字典值中的对象为空?

1 个答案:

答案 0 :(得分:1)

你的ajax电话

  var json= "{\"isSuccess\": false,    \"Errors\": {   \"e794bfa7-657b-482c-acdf-c5a3b6d2ce83\": [        {              \"ErrorMsg\": \"Invalid object name 'asfasf.CONTACT'.\",      \"Id\": \"63755f2a-1f02-480e-ab94-cafc62fd9634\",             \"ScriptContent\": \"CREATE VIEW [asfasf].Blala AS select * from [asfasf].[CONTACT]\",            \"ScriptDescription\": \"Script 6\",      \"ServerType\": \"SQLSERVER\",       \"Success\": false      }     ]  }}";

$.ajax({
        type: "POST",
        url: '/Default1/DisplayErrorsReportAsync?json=' + json,
        data: json,
        dataType: 'json',
        //contentType: false,
        //processData: false,
        success: function (response) {
            alert(response);
            $('#GeneralSection').html(response.responseText);
        },
        error: function (error) {
            $('#GeneralSection').html(error.responseText);
        }
    });

将json作为控制器中的字符串

在控制器使用中

  [HttpPost]
  public ActionResult DisplayErrorsReportAsync(string aaa)
  {    
    JObject o = JObject.Parse(json);
    JArray a = (JArray)o["ErrorReportModel"];
    ErrorReportModel model= a.ToObject<ErrorReportModel>();
  }

注意:使用Newtonsoft.Json