ASP.NET MVC:如何验证 ViewModel 中包装的模型?
对于我网站的登录页面,我想列出我网站的最新新闻,并显示一些字段以供用户登录。所以我想我应该制作一个登录视图模型 - 我称之为 LoginVM< /代码>。
LoginVM
包含用于登录字段的 Login
模型和用于新闻列表的 List
。
这是 Login
模型:
public class Login
{
[Required(ErrorMessage="Enter a username.")]
[DisplayName("Username")]
public string Username { get; set; }
[Required(ErrorMessage="Enter a password.")]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
}
这是 LoginVM
视图模型:
public class LoginVM
{
public Login login { get; set; }
public List<NewsItem> newsItems { get; set; }
}
这就是我陷入困境的地方。在我的登录控制器中,我传递了一个 LoginVM
。
[HttpPost]
public ActionResult Login(LoginVM model, FormCollection form)
{
if (ModelState.IsValid)
{
// What?
在代码中,我检查 ModelState
是否有效,如果视图模型实际上是 Login
模型,但现在是 LoginVM
,那么这会正常工作> 根本没有验证属性。
如何让 LoginVM
“遍历”其成员以验证所有成员?我以这种方式使用 ModelState 是否做了根本错误的事情?
For the login page of my website I would like to list the latest news for my site and also display a few fields to let the user log in. So I figured I should make a login view model - I call this LoginVM
.
LoginVM
contains a Login
model for the login fields and a List<NewsItem>
for the news listing.
This is the Login
model:
public class Login
{
[Required(ErrorMessage="Enter a username.")]
[DisplayName("Username")]
public string Username { get; set; }
[Required(ErrorMessage="Enter a password.")]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
}
This is the LoginVM
view model:
public class LoginVM
{
public Login login { get; set; }
public List<NewsItem> newsItems { get; set; }
}
This is where I get stuck. In my login controller, I get passed a LoginVM
.
[HttpPost]
public ActionResult Login(LoginVM model, FormCollection form)
{
if (ModelState.IsValid)
{
// What?
In the code I'm checking whether ModelState
is valid and this would work fine if the view model was actually the Login
model, but now it's LoginVM
which has no validation attributes at all.
How do I make LoginVM
"traverse" through its members to validate them all? Am I doing something fundamentally wrong using ModelState
in this manner?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在你的 ViewModel 中尝试这样做:
In your ViewModel try doing this:
或者,如果 newsItems 用于显示目的,并且不需要验证,那么您可以仅将 Login 模型传递到您的操作方法。
您还需要在视图中使用 EditFor 和 LabelFor 帮助器。
Alternatively if the newsItems are for display purposes, and don't need validating, then you can pass through just the Login model to your action method.
You will also want to use the EditFor and LabelFor helpers in your View.