模型中的 MVC 验证
我目前正在使用 DataAnnotations 来验证我的 MVC 2 应用程序。然而,我遇到了一个小问题。
我目前有一个 User 类型的对象,它有许多属性。所有这些都是必需的。
public class User
{
[Required(ErrorMessage = "Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "First name is required")]
public string Firstname { get; set; }
[Required(ErrorMessage = "Last name is required")]
public string Lastname { get; set; }
}
注册时,这些都使用 modelbinder 进行映射,一切都很好。但是,在“编辑我的详细信息”页面上,只能更新名字、姓氏和电子邮件。 每当视图发回并应用模型绑定时,我都会收到一条警告,“用户名/密码是必填字段”。尽管目前不需要。我想到了两种方法来解决这个问题,我认为这两种方法都不合适(但可能是错误的)
1:创建自定义视图模型。这可以正常工作,但需要将数据注释应用于此视图模型,这意味着对模型和用户对象进行重复验证。
2:包含渲染视图中的所有字段并将其回发。这存在安全风险,看起来真的很混乱,并且不能很好地扩展到复杂的视图模型。
任何人都可以推荐针对这种情况的最佳实践吗?
I'm currently using DataAnnotations to validate my MVC 2 app. However, I've ran into a small problem.
I currently have an object of type User which has a number of properties. All of which are required.
public class User
{
[Required(ErrorMessage = "Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "First name is required")]
public string Firstname { get; set; }
[Required(ErrorMessage = "Last name is required")]
public string Lastname { get; set; }
}
At signup, these are all mapped using the modelbinder and everything works great. However, on the "edit my detail" page only Firstname, Lastname and Email can be updated.
Whenever the view posts back and modelbinding is applied I'm getting an alert Username/Password is a required field. Even though it is not required at this point. I've thought of two ways to get around this neither of which I feel are suitable (but may be wrong)
1: Create a custom viewmodel. This will work fine, but data annotations will need to be applied to this viewmodel meaning duplicate validation on the model and the user object.
2: Include all the fields in the renderd view and post them back. This has security risks, seems really messy and wouldn't scale well to complex viewmodels.
Can anyone recommend a best practice for this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最近也有类似的问题:
需要在验证之前复制属性。作为回应,我建议创建自定义 ModelBinder 仅用于此特定操作,并且我仍然相信这是最佳解决方案。
There was similar question recently:
Needing to copy properties before validation. In response I have suggested creating custom ModelBinder for usage only in this particular action, and I still believe it's a best solution.