这是我的代码。下面的JSON不正确但我认为我很接近。控制器每次都获取空数据。任何帮助将不胜感激。
$( "#btnRegister" ).click(function() {
var personModel = {
FirstName: $("#txtFirstName").val(),
LastName: $("#txtLastName").val(),
Phone: $("#txtPhone").val(),
EmailAddress: $("#txtEmail").val()
};
var loginModel = {
UserName: $("#txtUserName").val(),
Password: $("#txtPassword").val()
};
var registerViewModel = {
WebUser: loginModel,
Person: personModel
};
$.ajax({
url: "@Url.Action("Register", "User")",
type: 'POST',
data: registerViewModel,
success: function(result) {
alert(result);
}
});
});
[HttpPost]
public JsonResult Register(RegisterViewModel registerViewModel)
{
string name = registerViewModel.Person.FirstName;
string username = registerViewModel.WebUser.UserName;
return Json(name);
}
public class RegisterViewModel
{
public WebUser WebUser { get; set; }
public Person Person { get; set; }
}
public class WebUser
{
[Key]
public string UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class Person
{
[Key]
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string EmailAddress { get; set; }
public string EmailConfirmation { get; set; }
public DateTime DateCreated { get; set; }
public string UserId { get; set; }
}
答案 0 :(得分:2)
ajax部分需要像这样
$.ajax({
url: "@Url.Action("Register", "User")",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(registerViewModel),
success: function(result) {
alert(result);
}
});
希望这有帮助!
答案 1 :(得分:1)
除了
之外,您正在搜索正在搜索的ID前面的哈希值$("#txtFirstName").val(),