从MVC控制器的jQuery收到一个复杂的对象 [英] Receive a complex object from jquery in mvc controller
问题描述
我试图从表单提交反对我的MVC控制器。
这里是JS:
<脚本>
功能submitForm(){
VAR usersRoles =新的阵列;
jQuery的(#dualSelectRoles2选项)。每个(函数(){
usersRoles.push(jQuery的(本).VAL());
});
VAR模型=新的对象();
。model.user =的jQuery('#selectUser)VAL();
model.roleslist = usersRoles;
的console.log(模式:'+'用户名:'+ model.user +'的角色:+ model.roleslist);
的console.log('JSON:+ JSON.stringify(型号));
jQuery.ajax({
键入:POST,
网址:@ Url.Action(
ADDUSER),
数据类型:JSON
//数据:{型号:JSON.stringify(usersRoles)},
数据:{
型号:JSON.stringify(模型)
},
成功:功能(数据){
警报(数据);
},
故障:功能(ERRMSG){
警报(ERRMSG);
}
});
}
现在取人必要的信息,并建立对象模式,然后将其发布到控制器。
下面是我的视图模型:
//从形式接收
公共类submitUserRolesViewModel
{
公共字符串userid {搞定;组; } 公开名单<串GT; rolesList {搞定;组; }
}
下面是我的控制器:
//邮报/角色/ ADDUSER
[HttpPost]
公众的ActionResult ADDUSER(StrsubmitUserRolesViewModel模型)
{
如果(型号!= NULL)
{ 返回JSON(成功);
}
其他
{
返回JSON(一个错误occoured);
}
}
我怎样才能收到控制器的JSON对象?现在,当目前一个帖子是由jQuery的执行我的模型为空。这意味着它是不正确的结合。我相信有在这里只是一些小错误的。
能否请你指出我要去的地方错了。
jQuery.ajax({
键入:POST,
网址:@ Url.Action(ADDUSER),
的contentType:应用/ JSON
数据:JSON.stringify(模型),
成功:功能(数据){警报(数据); },
错误:功能(ERRMSG){
警报(ERRMSG);
}
});
I am trying to submit a object from a form to my mvc controller. here is the 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);
}
});
}
now that fetches al the necessary info and builds the object "model" and then posts it to the controller.
Here is my view model:
//for receiving from form
public class submitUserRolesViewModel
{
public string userId { get; set; }
public List<String> rolesList { get; set; }
}
Here is my controller:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(StrsubmitUserRolesViewModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
How can I receive a json object in the controller? Now currently my model is null when a post is executed by the jquery. This means that it is not binding correctly. I am sure there is just something small wrong here.
Could you please point out where I am going wrong.
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);
}
});
这篇关于从MVC控制器的jQuery收到一个复杂的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!