반응형
jquery 및 ajax를 사용하여 json 개체를 mvc 컨트롤러에 게시합니다.
양식의 일부 값을 MVC 컨트롤러에 제출하려고 합니다.
컨트롤러는 다음과 같습니다.
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(String json)
{
Log.submit(json);
return View();
}
여기에 js가 있습니다.
<script>
function submitForm() {
var usersRoles = new Array;
$("#dualSelectRoles2 option").each(function () {
usersRoles.push($(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);
}
});
}
컨트롤러에서 디버깅할 때 매개 변수가 null로 표시됩니까?console.log(usersRoles)
데이터를 제공합니다.
내가 뭘 잘못하고 있는 거지?
컨트롤러에서 json 개체를 수신하려면 어떻게 해야 합니까?
당신의 코드에서 당신이 POST 액션으로 배열을 전달하려고 하는 것을 보았습니다.이 경우 아래의 작업 코드를 따릅니다.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(roles),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
그리고 관제사의 조치는 다음과 같습니다.
public ActionResult AddUser(List<String> Roles)
{
return null;
}
그리고 버튼을 클릭하면 -
json 문자열을 받는 대신 모델 바인딩이 더 좋습니다.예:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
내가 뭘 잘못하고 있는 거지?
당신은 html을 javascript 객체로 변환한 다음 JSON을 통해 json으로 두 번째 단계로 변환해야 합니다.문자열화.
컨트롤러에서 json 개체를 수신하려면 어떻게 해야 합니까?
보기:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>
컨트롤러:
public void PostRawJson(string json)
{
var order = System.Web.Helpers.Json.Decode(json);
var orderDate = order.OrderDate;
var secondOrderId = order.Item[1].Id;
}
언급URL : https://stackoverflow.com/questions/21571201/post-a-json-object-to-mvc-controller-with-jquery-and-ajax
반응형
'sourcecode' 카테고리의 다른 글
AJAX CORS 및 보안 고려 사항 이해 (0) | 2023.08.31 |
---|---|
PHP에서 업로드 형식의 파일 확장자 확인 (0) | 2023.08.31 |
우리가 조건부로 과제를 할 수 있습니까? (0) | 2023.08.31 |
도커가 마리아에게 링크를 작성합니다.DB (0) | 2023.08.31 |
파이썬에서 두 배의 정밀 부동값? (0) | 2023.08.26 |