与jquery ajax序列化的模型绑定无法正常工作

我有以下型号:

public class RegisterUseraccount { [Required] [DataType(DataType.EmailAddress)] [Display(Name = "E-Mail-Adresse")] public string Email { get; set; } [Required] [Display(Name = "Vorname")] public string FirstName { get; set; } [Required] [Display(Name = "Nachname")] public string LastName { get; set; } [Required] [DataType(DataType.Password)] [MinLength(5)] [Display(Name = "Passwort")] public string Password { get; set; } ... } 

以下观点:

 @using (Html.BeginForm("Register", "Useraccount", FormMethod.Post, new { id = "registerUseraccountForm", @class = "ym-form" })) { @Html.ValidationSummary(true) 
@Html.LabelForRequired(model => model.RegisterUseraccount.FirstName, null) @Html.EditorFor(model => model.RegisterUseraccount.FirstName, new { required = "required", name = "firstName" }) @Html.ValidationMessageFor(model => model.RegisterUseraccount.FirstName)
...

和我的JavaScript

 function sendForm(target) { alert(data); $.ajax({ url: target, type: "POST", contentType: 'application/json', data: $("#registerUseraccountForm").serialize(), success: ajaxOnSuccess, error: function (jqXHR, exception) { alert('Error message.'); } }); 

这是序列化的结果:

 RegisterUseraccount.FirstName=Peter&RegisterUseraccount.LastName=Miller&RegisterUseraccount.Email=miller%40gmail.com&RegisterUseraccount.Password=admin 

这是我试图POST到的控制器方法:

 [HttpPost] public ActionResult Register(RegisterUseraccount registerUseraccount) { ... } 

…但是数据没有到达方法,我收到错误404.我认为模型绑定器无法工作。

什么有效是以名称firstName = Peter发送的数据,但实际发送的是RegisterUseraccount.FirstName = Peter。

我该如何处理这个问题?

删除contentType: 'application/json',并将其修改为更好(从我的角度来看)

 $('#registerUseraccountForm').submit(function () { if ($(this).valid()) { $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), beforeSend: function () { }, complete: function () { }, ... 

也许你有这个模特

 public class YourModel { public RegisterUseraccount RegisterUseraccount { get; set; } } 

在这种情况下,您必须放置与您的操作对应的模型:

 [HttpPost] public ActionResult Register(YourModel model) { var registerUseraccount = model.RegisterUseraccount; ... } 

要么:

 @using (Html.BeginForm("Register", "Useraccount", FormMethod.Post, new { id = "registerUseraccountForm", @class = "ym-form" })) { @{ Html.RenderPartial("RegisterUseraccount"); } } 

RegisterUseraccount.cshtml

 @model YourNamespace.RegisterUseraccount @Html.ValidationSummary(true) 
@Html.LabelForRequired(model => model.FirstName, null) @Html.EditorFor(model => model.FirstName, new { required = "required", name = "firstName" }) @Html.ValidationMessageFor(model => model.FirstName)

但是你必须改变一些像@Html.ValidationSummary (true)这样的东西。

编辑

或者最简单:

 data: $("#registerUseraccountForm").serialize().replace("RegisterUseraccount.",""), 

编辑二

 data: $("#registerUseraccountForm").serialize().replace(/RegisterUseraccount./g,""),