Harshal Bulsara
Harshal Bulsara

Reputation: 8264

Send Nested JSON from view to model

I want to send Nested JSON from view to model, there are other questions about this problem but none of them have variable keys in their object.

JSON object:

"Login": {
    "userId": "harshal.bulsara",
    "userName": "Harshal Bulsara",
 },


"ListOfEntities": {
       "Patient": {
            0: "Add",
            1: "Edit"
          },
       "Practice": {
            0: "Add",
            1: "Edit",
            2: "List"
         },
   }

I was able to send data with key Login properly but I am not able to send ListOfEntities, Important thing here is that the key inside this JSON will not be same every time (Patient,practice) it may vary

Here is the model code:

public class authoritiesInfo
{
    public Dictionary<string, Dictionary<int,string>> ListOfEntities { get; set; }
}
public class dashboardModel
{
    public string userId { get; set; }
    public string userName { get; set; }

    public List<authoritiesInfo> auth { get; set; }
    public void createSession()
    {
        processing //
    }

}

Here is the controller code:

public class DashboardController : Controller
{
    // GET: Dashboard
    [HttpPost]
    public ActionResult Index(dashboardModel dm)
    {
        dm.createSession();
        return View();
    }
}

Code in view:

 var dt = [];
        dt.push({
            "userId": indexValue.value,
            "userName": $("#cmbName option:selected").text(),
            "auth": MY JSON mention above
        });


        $.ajax({
            type: "POST",
            url: '@Url.Action("Index", "Dashboard")',
            data: dt[0],
            crossDomain: true,
            success: function (data) {
               window.location.href = '@Url.Action("Page", "Dashboard")';
            },
            error: function (jqXHR, textStatus, error) {
                alert("Error");
            }
        });

Question: How can I send Nested JSON to controller, The JSON is coming from REST service which is also in my control of if there are other solution which required any modification in that is also welcome

Upvotes: 0

Views: 1107

Answers (1)

user3559349
user3559349

Reputation:

In order to bind to JSON, you must set the contentType: 'application/json' ajax option and stringify your data using JSON.stringify().

However, the JavaScriptSerializer wont bind nested Dictionaries, so you will change your model(s) to accept nested Lists

public class authoritiesInfo
{
    public string Name { get; set; }
    public List<string> Values { get; set; }
}
public class dashboardModel
{
    public string userId { get; set; }
    public string userName { get; set; }
    public List<authoritiesInfo> auth { get; set; }
}

and the data will then be

var data = {
    userId: 'harshal.bulsara',
    userName: 'Harshal Bulsara',
    auth: [
        {
            Name: 'Patient',
            Values: [ 'Add', 'Edit' ]
        },
        {
            Name: 'Practice',
            Values: ['Add', 'Edit', 'List']
        }
    ]
};

and the ajax

$.ajax({
    url: '@Url.Action("Index", "Dashboard")',
    contentType: 'application/json',
    data: JSON.stringify({ dm: data }),
    type: 'POST',
    success: function (data) {
        ....
    }
});

which will then bind to

[HttpPost]
public ActionResult Index(dashboardModel dm)

Side note: If you need a collection of objects such as [{ 0: 'Add' },{ 1, 'Edit' }] rather than a collection of strings [ 'Add', 'Edit' ], then create an additional class (say Item) with properties int ID and string Name then change public List<string> Values { get; set; } to public List<Item> Values { get; set; } and change the data to

Name: 'Patient',
Values: [
    { ID: 2, Name: 'Add' },
    { ID: 3, Name: 'Edit' },
]

Upvotes: 1

Related Questions