How to receive JSON as an MVC 5 action method parameter

Posted Chuck Lu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了How to receive JSON as an MVC 5 action method parameter相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

How to create an rpm package

How to throw an error in MySql procedure?

how to be an efficient man

[NPM + React] Prepare a Custom React Hook to be Published as an npm Package

How to make an HTTP request

HOW TO USE SCANIA XCOM RESET AN ECU