码迷,mamicode.com
首页 > Web开发 > 详细

How to receive JSON as an MVC 5 action method parameter

时间:2019-10-10 20:44:52      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:ajax   head   obj   arc   ati   text   app   url   fir   

How to receive JSON as an MVC 5 action method parameter

 解答1

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 - 

 解答2

fwiw, this didn‘t work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

 解答3

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren‘t binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

 

Posting JSON Data to ASP.NET MVC

Take a look at Phil Haack‘s post on model binding JSON data.

The problem is that the default model binder doesn‘t serialize JSON properly. You need some sort of ValueProvider OR you could write a custom model binder:

 

How to receive JSON as an MVC 5 action method parameter

标签:ajax   head   obj   arc   ati   text   app   url   fir   

原文地址:https://www.cnblogs.com/chucklu/p/11650031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!