我有一个 ViewModel,它有一个模型和一些额外的属性。模型上和属性上都有验证,但执行时只检查模型上的验证,属性上的验证被忽略。
模型:
[MetadataType(typeof(Customer_Validation))]
public partial class Customer
{
}
public class Customer_Validation
{
[Required(ErrorMessage="Please enter your First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your Last name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Sorry, e-mail cannot be empty")]
[Email(ErrorMessage="Invalid e-mail")]
public string Email { get; set; }
}
View 模型
public class RegisterViewModel
{
public Customer NewCustomer { get; private set; }
[Required(ErrorMessage="Required")]
public string Password { get; private set; }
public RegisterViewModel(Customer customer, string password)
{
NewCustomer = customer;
Password = password;
}
}
Controller
public ActionResult Create()
{
Customer customer = new Customer();
RegisterViewModel model = new RegisterViewModel(customer, "");
return View(model);
}
[HttpPost]
public ActionResult Create(Customer newCustomer, string password)
{
if (ModelState.IsValid)
{
try
{
// code to save to database, redirect to other page
}
catch
{
RegisterViewModel model = new RegisterViewModel(newCustomer, password);
return View(model);
}
}
else
{
RegisterViewModel model = new RegisterViewModel(newCustomer, password);
return View(model);
}
}
风景
@using (Html.BeginForm())
{
<table>
<tr>
<td>First Name:</td>
<td>@Html.TextBoxFor(m => m.NewCustomer.FirstName)</td>
<td>@Html.ValidationMessageFor(m => m.NewCustomer.FirstName)</td>
</tr>
<tr>
<td>Last Name:</td>
<td>@Html.TextBoxFor(m => m.NewCustomer.LastName)</td>
<td>@Html.ValidationMessageFor(m => m.NewCustomer.LastName)</td>
</tr>
<tr>
<td>E-mail:</td>
<td>@Html.TextBoxFor(m => m.NewCustomer.Email)</td>
<td>@Html.ValidationMessageFor(m => m.NewCustomer.Email)</td>
</tr>
<tr>
<td>Password:</td>
<td>@Html.TextBoxFor(m => m.Password)</td>
<td>@Html.ValidationMessageFor(m => m.Password)</td>
</tr>
</table>
<input type="submit" value="Register" />
}
如果我提交表单时将密码留空,它就会通过。如果我将客户字段留空,它会显示错误(密码字段除外)
最佳答案
这很正常。您的 POST Controller 操作将 Customer
作为参数而不是 View 模型。验证由模型绑定(bind)器执行,因此当模型绑定(bind)器尝试从请求参数绑定(bind) Customer 对象时,它将调用验证。如果您希望在此 View 模型上执行验证,您的 POST 操作需要将 View 模型作为参数。目前,您在 post 操作中对该 View 模型所做的所有操作都是调用构造函数,而调用构造函数根本不会触发任何验证。
所以你的 POST Action 应该变成:
[HttpPost]
public ActionResult Create(RegisterViewModel newCustomer)
{
if (ModelState.IsValid)
{
// code to save to database, redirect to other page
}
else
{
return View(newCustomer);
}
}
请注意您不需要将密码作为第二个操作参数传递,因为它已经是您 View 模型的一部分。
关于c# - ASP.NET MVC 模型验证不适用于 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4358791/