3

I need some help with the hereunder please. I have these 2 models and the method I will be using them in hereunder.

public class RoleModel
{
    public string Name { get; set; }
    public string Description { get; set; }
    public List<PermissionGroupModel> PermissionGroups { get; set; }
}

public class PermissionGroupModel
{
    public int PermissionGroupID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

 [HttpPost]
 public bool CreateRole(RoleModel r){
  //code goes here
}

I am trying to post data to the CreateRole() method via AJAX and using a debug break to inspect the 'r' parameter to see if the model is getting populated. This is the AJAX call I am using to test it out.

$.ajax({
        type: "POST",
        url: "/BackOffice/CreateRole",
        data:  {"Name": "Test Name", "Description": "Test Desc", "PermissionGroups": ["Name": "Group Name", "Description": "Test Desc"]},
        success: function (data) {},
        complete: function (data) {}
      });

When the request is made and I inspect the parameter in visual studio. The RoleModel Name and Description Keys are populated and PermissionGroups Count is 1 but the keys in PermissionGroups are not being populated.

Can anyone suggest any way I can pass a JSON object with a list of objects in it.

Thanks in advance.

Matthew Pulis
  • 33
  • 1
  • 3
  • You're not sending the PermissionGroupID property of the PermissionGroups items, how do you expect that it will be populated? – Vi100 Dec 02 '15 at 17:56

1 Answers1

1

The javascript object you are sending is not proper.

 "PermissionGroups": ["Name": "Group Name", "Description": "Test Desc"]

In your viewmodel, PermissionGroups is a collection of PermissionGroupModel items. But you are not passing it like this. The above code is sending 4 string items as the value of the PermissionGroups property. You need to wrap each item in the collection with { and }

Also ,for model binding to happen on complex objects, you need to convert your javascript object to a json string using JSON.stringify method and specify the contentType property when making the ajax call. The contentType property value should be "application/json"

The contentType property tells the server that the data we are sending is in Json format.

 var d = {
            "Name": "Test Name", "Description": "Test Desc",
            "PermissionGroups": [{ "Name": "Group Name", "Description": "Test Desc" }]
         };

 $.ajax({
            type: "POST",
            url: "/BackOffice/CreateRole",
            contentType: "application/json",
            data: JSON.stringify(d) ,
            success: function (data) {  console.log(data); },
            complete: function (data) {}
       });

Also, It is a good idea to use the Url.Action helper method to build the urls to action methods.

So replace url: "/BackOffice/CreateRole" with url: "@Url.Action("CreateRole","BackOffice")"

Shyju
  • 214,206
  • 104
  • 411
  • 497