我想在我的UserViewModel
中重新使用我的User
類,因爲它太大,屬性太多。嵌套類中的比較屬性
public class User
{
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
/* ... many other properties */
}
我UserViewModel
擁有財產User
和ConfirmEmail
和ConfirmPassword
性能。
public class UserViewModel
{
public User User;
[DataType(DataType.EmailAddress)]
[Compare("User.Email")]
public string ConfirmEmail { get; set; }
[DataType(DataType.Password)]
[Compare("User.Password")]
public string ConfirmPassword { get; set; }
}
當我tryed [Compare("Password")]
錯誤是:
酒店UserViewModel.Password找不到。
而且隨着[Compare("User.Password")]
錯誤是:
酒店UserViewModel.User.Password找不到。
有沒有辦法做到這一點?
編輯:解決的辦法:
我tryed againd的thepirat000答案,但也有一些變化:
UserViewModel.cs
public class UserViewModel
{
public User User;
public string UserEmail
{
get { return User.Email; }
set { User.Email = value; }
}
[DataType(DataType.EmailAddress)]
[Compare("UserEmail")]
public string ConfirmEmail { get; set; }
}
用戶/ Create.cshtml
在我的觀點,而不是:
<div class="form-group">
@Html.LabelFor(model => model.User.Email)
@Html.EditorFor(model => model.User.Email)
</div>
<div class="form-group">
@Html.ValidationMessageFor(model => model.User.Email)
</div>
<div class="form-group pad-top">
@Html.LabelFor(model => model.ConfirmEmail)
@Html.EditorFor(model => model.ConfirmEmail)
@Html.ValidationMessageFor(model => model.ConfirmEmail)
</div>
我改變model => model.User.Email
到model => model.UserEmail
:
<div class="form-group">
@Html.LabelFor(model => model.UserEmail)
@Html.EditorFor(model => model.UserEmail)
</div>
<div class="form-group">
@Html.ValidationMessageFor(model => model.UserEmail)
</div>
<div class="form-group pad-top">
@Html.LabelFor(model => model.ConfirmEmail)
@Html.EditorFor(model => model.ConfirmEmail)
@Html.ValidationMessageFor(model => model.ConfirmEmail)
</div>
現在兩個客戶端和服務器端進行驗證。
我已經tryed這種解決方法也是如此,但這樣一來我的UserViewModel.User。電子郵件不會被填充,並會在控制器方法「ActionResult Create(UserViewModel user)」上引發錯誤。 –
我再次嘗試了一些更改並立即開始工作!我們也需要設置屬性。謝謝你的想法。 –