簡體   English   中英

MVC3-將Json模型傳遞給控制器​​(詞典)

[英]MVC3 - Passing Json Model to Controller (Dictionary)

當我從ajax調用接收到Json Data時,我的模型為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;
    }

收到的模型如下所示:

收到模型

為什么我的字典值中的對象為null?

你的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM