当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Passing JSON Object and List of Objects to ASP.Net Controller

问题描述:

This question already has an answer here:

  • Post JSON array to mvc controller

    3 answers

网友答案:

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")"

分享给朋友:
您可能感兴趣的文章:
随机阅读: