本文介绍了发布一个JSON对象MVC控制器与jQuery和AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从表单提交一些值到我的MVC控制器。
I am trying to submit some values from a form to my mvc controller.
下面是我的控制器:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(String json)
{
Log.submit(json);
return View();
}
这里是JS:
here is the 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);
}
});
}
当我调试控制器让我的参数为空?该的console.log(usersRoles)
给我的数据。
When I debug on the controller I get my parameter to be null?The console.log(usersRoles)
gives me data.
我在做什么错误?
如何在控制器收到一个JSON对象?
How can I receive a json object in the controller?
推荐答案
我在你的code,你试图传递一个数组POST操作看。在这种情况下,按照以下工作code -
I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -
<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()"/>
和控制器动作将是 -
And the controller action is going to be -
public ActionResult AddUser(List<String> Roles)
{
return null;
}
然后当你点击按钮 -
Then when you click on the button -
这篇关于发布一个JSON对象MVC控制器与jQuery和AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!