如何将JSON作为MVC 5操作方法参数接收

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


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


我尝试了以下方法:1:


    //Post/ Roles/AddUser

    [HttpPost]

    public ActionResult AddUser(String model)

    {

        if(model != null)

        {

            return Json("Success");

        }else

        {

            return Json("An Error Has occoured");

        }


    }

这给了我输入一个空值。


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错误?(这表示未正确绑定)。


这是我的jQuery代码:


<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对象?


神不在的星期二
浏览 423回答 3
3回答

拉丁的传说

这里有几个问题。首先,您需要确保将JSON对象绑定回控制器中的模型。这是通过更改来完成的data: JSON.stringify(usersRoles),至data: { model: JSON.stringify(usersRoles) },其次,您的jQuery调用没有正确绑定类型。如果删除contentType: "application/json; charset=utf-8",它会固有地绑定回字符串。一起使用第一个ActionResult方法和以下jquery ajax调用:&nbsp; &nbsp; jQuery.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; url: "@Url.Action("AddUser")",&nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; data: { model: JSON.stringify(usersRoles) },&nbsp; &nbsp; &nbsp; &nbsp; success: function (data) { alert(data); },&nbsp; &nbsp; &nbsp; &nbsp; failure: function (errMsg) {&nbsp; &nbsp; &nbsp; &nbsp; alert(errMsg);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP