我有ViewModel裏面有一個模型和一些額外的屬性。對模型和屬性進行了驗證,但是在執行時只檢查模型上的驗證,忽略屬性中的驗證。ASP.NET MVC模型驗證不能在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; }
}
視圖模型
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;
}
}
的控制器
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" />
}
如果我提交的表格留下密碼空白它讓我們通過。如果我留下空的客戶字段它確實顯示錯誤(密碼字段除外)
這聽起來很合邏輯,可以幫我修復它。我將單獨在控制器內部進行其他屬性驗證,直到找到使用模型驗證的最佳解決方案。非常感謝。 – Nestor 2010-12-06 04:09:01