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

查看:34
本文介绍了如何接收 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 中的模型绑定存在问题.在此处阅读全文.相反,创建一个自定义模型绑定器来获取字典作为控制器操作的参数.

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 可以有 RoleModel 列表.

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

所以现在当 post 发生时,你可以在 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天全站免登陆