허당 레몬도리

출처 : http://stackoverflow.com/questions/21578814/how-to-receive-json-in-a-mvc-5-action-method-as-a-paramter

Unfortunately Dictionary got always problem with Model Binding in MVC. Read the full story here. So we have to create our own custom model binder to get the Dictionary as a parameter to our controller action.

To solve your requirement, here is the working solution -

First create your ViewModels in following way. PersonModel can have list of RoleModels.

public class PersonModel
{
    public List<RoleModel> Roles { get; set; }
    public string Name { get; set; }
}

public class RoleModel
{
    public string RoleName { get; set;}
    public string Description { get; set;}
}

Then have a index action which will be serving basic index view -

    public ActionResult Index()
    {
        return View();
    }

Index view will be having following JQuery AJAX POST operation -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $('#click1').click(function (e) {

            var jsonObject = {
                "Name" : "Rami",
                "Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
            };

            $.ajax({
                url: "@Url.Action("AddUser")",
                type: "POST",
                data: JSON.stringify(jsonObject),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                    alert(response.responseText);
            },
                success: function (response) {
                    alert(response);
                }
            });

        });
    });
</script>

<input type="button" value="click1" id="click1" />

Index action posts to AddUser action -

    [HttpPost]
    public ActionResult AddUser(PersonModel model)
    {
        if (model != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }

    }

So now when the post happens you can get all the posted data in the model parameter of action.

enter image description here

shareimprove this answer


profile

허당 레몬도리

@LemonDory

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!