我的問題與this question類似,但我仍然在驗證服務器端和客戶端方面存在問題。我想對兩個屬性進行比較,並設置在不同的模型中。複雜模型上的ASP.NET MVC 4驗證 - 模型未在服務器端進行驗證
我的型號如下:
public class User{
public string Password { get; set; }
}
public class UserRegisterViewModel {
public User User{ get; set; }
//This is suggested in linked question - as Compare can only work with local property
public string Password
{
get{return this.User.Password;}
}
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Passwords must match")]
[Required(ErrorMessage = "Confirm password is required")]
[DisplayName("Confirm Password")]
public string CPassword { get; set; }
}
我的控制器操作是:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(UserRegisterViewModel model)
{
if (ModelState.IsValid) //This conditions is false
{
}
return View();
}
它重定向到再次驗證錯誤說Password must match
註冊頁面。有人可以幫忙嗎?我檢查了this question它有點幫助,但不完全。
如果我改變模型結構如下圖所示,比我得到一個錯誤說:Could not find a property named User.Password
:
public class UserRegisterViewModel {
public User User{ get; set; }
[DataType(DataType.Password)]
[Compare("User.Password", ErrorMessage = "Passwords must match")]
[Required(ErrorMessage = "Confirm password is required")]
[DisplayName("Confirm Password")]
public string CPassword { get; set; }
}
編輯
我CSHTML頁面的代碼如下圖所示。
<p>
@Html.LabelFor(model => model.User.Password)
@Html.PasswordFor(model => model.User.Password, new { @class = "wd189 inputtext" })
@Html.ValidationMessageFor(model => model.User.Password)
</p>
<p>
@Html.LabelFor(model => model.CPassword)
@Html.PasswordFor(model => model.CPassword, new { @class = "wd189 inputtext" })
@Html.ValidationMessageFor(model => model.CPassword)
</p>
你能張貼您查看的代碼和'HttpGet'你'Register'行動結果? – bump
@bump添加了View的代碼,如何獲取httpget?對不起,但我是新來的這個。 –
但是你組織你的UserRegisterViewModel的方式(與
[Compare("User.Password", ErrorMessage = "Passwords must match")]
是你提供的鏈接的確切問題(另一個問題),這就是爲什麼另外引入了一些額外的屬性「密碼」 – Agat