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");
}
}
그 결과 내 입력값이 무효가 되었지
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 객체를 수신하기만 하면 됩니까?
MVC의 모델 바인딩에 문제가 있습니다. 자세한 내용은 여기를 참조하십시오.대신, 사용자 정의 모델 바인더를 작성하여 컨트롤러 수행에 대한 매개변수로 사전을 가져오십시오.
고객의 요구를 해결하기 위한 유효한 솔루션은 다음과 같습니다.
먼저 다음과 같은 방법으로 View Model을 작성합니다.Person Model은 역할 모델 목록을 가질 수 있습니다.
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" />
액션 투고를 Add User 액션에 인덱스 -
[HttpPost]
public ActionResult AddUser(PersonModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
투고가 발생하면 액션의 모델 파라미터로 투고된 모든 데이터를 가져올 수 있습니다.
업데이트:
asp.net 코어의 경우 액션파라미터로 JSON 데이터를 취득하려면 컨트롤러 액션에서 파라미터 이름 앞에 속성을 추가해야 합니다.주의: ASP를 사용하는 경우.NET Core 2.1에서는,[ApiController]복잡한 액션 메서드 파라미터의 [FromBody]바인딩 소스를 자동으로 추론하는 속성입니다.(Doc)

여기에는 몇 가지 문제가 있습니다.먼저 컨트롤러의 모델에 JSON 개체를 바인드해야 합니다.이것은 변경에 의해서 행해집니다.
data: JSON.stringify(usersRoles),
로.
data: { model: JSON.stringify(usersRoles) },
둘째, jquery 호출에서 유형을 올바르게 바인딩하지 않습니다.를 삭제하면
contentType: "application/json; charset=utf-8",
기본적으로 문자열로 바인드됩니다.
모두 함께 첫 번째 ActionResult 메서드와 다음 jquery ajax 콜을 사용합니다.
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);
}
});
문자열 배열을 보내고 있습니다.
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
따라서 그에 따라 모델 유형을 변경하십시오.
public ActionResult AddUser(List<string> model)
{
}
fwiw, 이건 내가 에이잭스 콜에서 이걸 받기 전까진 통하지 않았어.
contentType: "application/json; charset=utf-8",
ASP를 사용합니다.넷 MVC 4
언급URL : https://stackoverflow.com/questions/21578814/how-to-receive-json-as-an-mvc-5-action-method-parameter
'programing' 카테고리의 다른 글
| 한 페이지 어플리케이션이 필요한 이유는 무엇입니까? (0) | 2023.03.20 |
|---|---|
| angularjs: ng-switch 내의 여러 값: 다음 경우 (0) | 2023.03.20 |
| 연락처 폼7을 사용하여 POST 데이터를 캡처하는 방법 (0) | 2023.03.20 |
| posts_search의 커스텀 (0) | 2023.03.20 |
| 사용자가 이미 Memberpress 제품을 구독한 경우 어떻게 탐지할 수 있습니까? (0) | 2023.03.20 |