我正在阅读教程并尝试习惯使用 ViewModels 和 Validation。我不确定验证是在主模型还是视图模型上进行,我假设它在 ViewModel 上。但是,如果我试图继承一个类属性,那么在 ViewModel 上添加验证似乎没有意义,所以我把它留在了模型本身上,但错误没有出现。也许模型效率低下,需要重新排列一下?
名称型号
public class name {
[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
public string first { get; set; }
public string middle { get; set; }
[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
public string last { get; set; }
public string otherstuffnotneededontheview { get; set; }
}
注册视图模型
public class RegisterViewModel {
public name fname { get; set; }
public name lname { get; set; }
}
看法
@model Project.ViewModels.RegisterViewModel
@using (Html.BeginForm())
{
<label>
@Html.TextBoxFor(model => model.fname.first)
@Html.ValidationMessageFor(model => model.fname.first)
</label>
<label>
@Html.TextBoxFor(model => model.lname.last)
@Html.ValidationMessageFor(model => model.lname.last)
</label>
<input type="submit" />
}
控制器
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
return View(model);
}