programing

MVC 5 작업 메서드 매개 변수로 JSON을받는 방법

nasanasas 2020. 11. 18. 09:12
반응형

MVC 5 작업 메서드 매개 변수로 JSON을받는 방법


나는 액션 컨트롤러에서 JSON 객체를 받으려고 웹을 통해 오후 내내 크롤링을 시도해 왔습니다.

이를 수행하는 정확하고 쉬운 방법은 무엇입니까?

나는 다음을 시도했다 : 1 :

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

    }

내 입력에 null 값을 제공했습니다.

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 객체를받는 것뿐입니까?


불행히도 Dictionary는 MVC의 모델 바인딩에 문제가 있습니다. 여기에서 전체 내용을 읽어보십시오 . 대신 사용자 지정 모델 바인더를 만들어 컨트롤러 작업에 대한 매개 변수로 사전을 가져옵니다.

요구 사항을 해결하기위한 작업 솔루션은 다음과 같습니다.

먼저 다음과 같은 방법으로 ViewModel을 만듭니다. PersonModel은 RoleModel 목록을 가질 수 있습니다.

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

그런 다음 기본 색인보기를 제공 할 색인 작업이 있습니다.

    public ActionResult Index()
    {
        return View();
    }

인덱스보기에는 다음 JQuery AJAX POST 작업이 있습니다.

<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 작업에 대한 작업 게시물 색인 생성-

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

    }

이제 게시물이 발생하면 행동의 모델 매개 변수에서 게시 된 모든 데이터를 얻을 수 있습니다.

최신 정보:

asp.net 코어의 경우 JSON 데이터를 작업 매개 변수로 가져 오려면 [FromBody]컨트롤러 작업에서 매개 변수 이름 앞에 속성을 추가해야합니다 . 참고 : ASP.NET Core 2.1을 사용하는 경우 [ApiController]특성을 사용 하여 복잡한 작업 메서드 매개 변수에 대한 [FromBody] 바인딩 소스를 자동으로 유추 할 수도 있습니다 . (문서)

enter image description here


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

You are sending a array of string

var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
    usersRoles.push(jQuery(this).val());
});   

So change model type accordingly

 public ActionResult AddUser(List<string> model)
 {
 }

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.

참고URL : https://stackoverflow.com/questions/21578814/how-to-receive-json-as-an-mvc-5-action-method-parameter

반응형