我正在开发asp.net mvc web应用程序。我有一个用于注册用户信息的表单。单击按钮时会写入保存操作。而我正试图将多个模型传递给控制器。但是在控制器中它变得无效。我如何解决这个问题..我已经尝试了一些解决方案。
这是我的例子 - 请检查:
我有一个父模型:
public class ParentUsers
{
public Login loginModel { get; set; }
public Details registerModel { get; set; }
}
Jquery函数
$("#registerLE").click(function () {
var form = $("#registration");
var validatable = form.kendoValidator().data("kendoValidator");
debugger
if (validatable.validate()==true) {
var parentModel = {
loginModel :{
Username: $('input[name=uname]').val(),
Password: $('input[name=password]').val(),
Role: 'LE'
},
registerModel: {
name: $('input[name=firstname]').val(),
userId:1
}
}
$.ajax({
type: "POST",
url: "/Home/Register",
data: { "parentModel": parentModel },
datatype: "json",
cache: false,
success: function (data) {
alert("You Multiple Data Passed Successfully");
},
error: function (xhr) {
alert('No Valid Data');
}
});
}
});
控制器方法:
public ActionResult Register(ParentUsers parentModel)
{
//...after save..//
return View("Login");
}
请帮助
答案 0 :(得分:0)
你需要在你的ajax中稍微改变一下。我已经测试了你的代码,它的工作正常我的一面
行动方法:
public ActionResult SubmitMethod(ParentUsers parentuser)
{
//do stuff here
return Json( "" , JsonRequestBehavior.AllowGet);
}
模态:
public class ParentUsers
{
public loginModel loginModel { get; set; }
public Details registerModel { get; set; }
}
public class loginModel {
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
public class Details {
public string name { get; set; }
public int Id { get; set; }
}
Ajax代码:
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<input type="button" id="btnPost" value="Gel Users" />
<script>
$(document).ready(function () {
$('#btnPost').click(function () {
alert('btnPost');
var loginModelObj = {
Username:"UsernameValue",
Password:"PasswordValue",
Role:"RoleValue",
};
var registerModelObj = {
name:"nameValue",
Id:1
};
var SendObject = {
loginModel: loginModelObj, //loginModel same name as in Modal
registerModel: registerModelObj, //registerModel same name as in Modal
}
$.ajax({
method: 'POST',
url: '/Test/SubmitMethod',
contentType: 'application/json', // send data type to server
dataType: 'json', //return type of data from server
data:JSON.stringify(SendObject),
// asyn: false,
success: function (data, status, xhr) {
// do stuff here
},
error: function (response, status, xhr) {
alert(response.statusText);
}
})
})
})
</script>