如何将JSON作为MVC 5操作方法参数接收 [英] How to receive JSON as an MVC 5 action method parameter

查看:98
本文介绍了如何将JSON作为MVC 5操作方法参数接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在整个下午都在尝试爬网,试图在动作控制器中接收JSON对象.

I have been trying the whole afternoon crawling through the web trying to receive a JSON object in the action controller.

什么是正确的或更简单的方法?

What is the correct and or easier way to go about doing it?

我尝试了以下方法: 1:

I have tried the following: 1:

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

    }

在输入中给了我一个空值.

Which gave me a null value on my input.

2:

    //Post/ Roles/AddUser
    [HttpPost]
    public ActionResult AddUser(IDictionary<string, object> model)
    {
        if(model != null)
        {
            return Json("Success");
        }else
        {
            return Json("An Error Has occoured");
        }

    }

在尝试向其发布的jquery端给我500错误? (这表示未正确绑定).

which gives me a 500 error on the jquery side which is trying to post to it? (meaning that it didn't bind correctly).

这是我的jQuery代码:

here is my jQuery code:

<script>
function submitForm() {

    var usersRoles = new Array;
    jQuery("#dualSelectRoles2 option").each(function () {
        usersRoles.push(jQuery(this).val());
    });
    console.log(usersRoles);

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(usersRoles),
        success: function (data) { alert(data); },
        failure: function (errMsg) {
            alert(errMsg);
        }
    });
}

我要做的就是在我的mvc操作中接收我的JSON对象?

All I want to do is receive my JSON object in my mvc action?

推荐答案

不幸的是,Dictionary在MVC中存在模型绑定问题. 在此处阅读全文.而是创建一个自定义模型联编程序,以将Dictionary作为控制器操作的参数.

Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.

要解决您的要求,这是可行的解决方案-

To solve your requirement, here is the working solution -

首先按照以下方式创建ViewModel. PersonModel可以具有RoleModels列表.

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

索引视图将具有以下JQuery AJAX POST操作-

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

将索引操作发布到AddUser操作-

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

    }

因此,现在发布时,您可以在action的模型参数中获取所有发布的数据.

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

更新:

对于asp.net核心,要获取JSON数据作为操作参数,应在控制器操作中的参数名称之前添加 [FromBody] 属性.注意:如果使用的是ASP.NET Core 2.1,则还可以使用[ApiController]属性为复杂的操作方法参数自动推断[FromBody]绑定源. (文档)

For asp.net core, to get JSON data as your action parameter you should add the [FromBody] attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController] attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)

这篇关于如何将JSON作为MVC 5操作方法参数接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆