我有一个简单的模型和视图。那么,当试图绑定我的模型时,模型绑定器似乎失败了,因为我总是在控制器动作中收到NULL。我做错了什么?
剃刀代码:
@model BikeSharing.Views.Shared.Widgets.Popups.LoginInputModel
@using (Ajax.BeginForm("Login",null, new AjaxOptions
{
UpdateTargetId = "login-partial-update",
HttpMethod = "POST"
}, new { id = "js-form-login" }))
{
@Html.TextBoxFor(x => x.Email, new {placeholder = "Email address"})
<div class="errormessage">
@Html.ValidationMessageFor(x=>x.Email)
</div>
@Html.PasswordFor(x => x.Password, new {placeholder = "Password"})
<div class="errormessage">
@Html.ValidationMessageFor(x => x.Password)
</div>
}
控制器操作:
[HttpPost]
public ActionResult Login(LoginInputModel lmod)
{
if (ModelState.IsValid)
{
// this code is never reached because lmod is always NULL
}
return PartialView("Widgets/Popups/_LoginInput", lmod);
}
型号代码:
public class LoginInputModel
{
[Required(ErrorMessage = "Your email address is required.")]
[EmailAddress]
public string Email { get; private set; }
[Required(ErrorMessage = "Please provide your password.")]
[MinLength(6,ErrorMessage = "Your password is too short.")]
[MaxLength(50, ErrorMessage = "Your password is too long.")]
public string Password { get; private set; }
public LoginInputModel()
{
}
public LoginInputModel(string email, string password)
{
Email = email;
Password = password;
}
}
表单提交是通过jquery-unobtrusive-ajax和Ajax.BeginForm()
完成的
我只是通过$('#js-form-login').submit();
在浏览器中呈现HTML:
<form action="/Home/Login" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#login-partial-update" id="js-form-login" method="post" novalidate="novalidate">
<input data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="Your email address is required." id="Email" name="Email" placeholder="Email address" type="text" value="">
<div class="errormessage">
<span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
<input data-val="true" data-val-maxlength="Your password is too long." data-val-maxlength-max="50" data-val-minlength="Your password is too short." data-val-minlength-min="6" data-val-required="Please provide your password." id="Password" name="Password" placeholder="Password" type="password">
<div class="errormessage">
<span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span>
</div>
</form>
答案 0 :(得分:1)
尝试将FormBody
前缀添加到ModelBinder,以查看POST正文。
[HttpPost]
public ActionResult Login([FromBody]LoginInputModel lmod)
{
if (ModelState.IsValid)
{
// this code is never reached because lmod is always NULL
}
return PartialView("Widgets/Popups/_LoginInput", lmod);
}