我正在尝试将对象从表单提交到我的 mvc Controller 。 这是 js:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.user = jQuery('#selectUser').val();
model.roleslist = usersRoles;
console.log('model: ' + 'user: ' + model.user + 'roles: ' + model.roleslist);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "@Url.Action("
AddUser ")",
dataType: "json",
//data: { model: JSON.stringify(usersRoles) },
data: {
model: JSON.stringify(model)
},
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
现在获取所有必要的信息并构建对象“模型”,然后将其发布到 Controller 。
这是我的 View 模型:
//for receiving from form
public class submitUserRolesViewModel
{
public string userId { get; set; }
public List<String> rolesList { get; set; }
}
这是我的 Controller :
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(StrsubmitUserRolesViewModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
如何在 Controller 中接收 json 对象?现在,当 jquery 执行帖子时,我的模型为空。这意味着它没有正确绑定(bind)。我确信这里只是出了点小问题。
你能指出我哪里错了吗
最佳答案
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { alert(data); },
error: function (errMsg) {
alert(errMsg);
}
});
关于javascript - 在 mvc Controller 中从 jquery 接收一个复杂的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21595781/