billybob
billybob

Reputation: 3008

MVC3 - Passing Json Model to Controller (Dictionary)

When I receive the Json Data from the ajax call, my model is null:

Here's my model in C# :

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

That's my ajax call:

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

the Json data (StringJsonLastExecutionReportModel) looks like this and it's valid:

{
    "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
            }
        ]
    }
}

Here's my controller method:

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

the received model looks like this :

Received Model

Why the object in my value of my dictionary is null?

Upvotes: 1

Views: 398

Answers (1)

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

Your ajax call

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

Take json as string in your controller

in controller use

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

Note : use Newtonsoft.Json

Upvotes: 1

Related Questions