我目前正在使用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; }
}
在注册时,这些都是使用模型绑定器映射的,一切都很好。但是,在“编辑我的详细信息”页面上,只能更新名字,姓氏和电子邮件。 每当视图回发并且应用了模型绑定时,我都会收到警报用户名/密码是必填字段。即使此时不需要。我想到了两种解决这个问题的方法,我认为这两种方法都不合适(但可能是错误的)
1:创建自定义视图模型。这样可以正常工作,但是需要将数据注释应用于此视图模型,这意味着对模型和用户对象进行重复验证。
2:在渲染视图中包含所有字段并将其发回。这有安全隐患,看起来非常混乱,无法很好地扩展到复杂的视图模型。
有人可以推荐这种情况的最佳做法吗?
答案 0 :(得分:1)
最近有类似的问题: Needing to copy properties before validation。作为回应,我建议创建自定义ModelBinder仅用于此特定操作,我仍然认为这是最佳解决方案。
答案 1 :(得分:0)
DataType
Specify the datatype of a property
DisplayName
specify the display name for a property.
DisplayFormat
specify the display format for a property like different format for Date proerty.
Required
Specify a property as required.
ReqularExpression
validate the value of a property by specified regular expression pattern.
Range
validate the value of a property with in a specified range of values.
StringLength
specify min and max length for a string property.
MaxLength
specify max length for a string property.
Bind
specify fields to include or exclude when adding parameter or form values to model properties.
ScaffoldColumn
specify fields for hiding from editor forms.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Employee.Models
{
[Bind(Exclude = "EmpId")]
public class Employee
{
[ScaffoldColumn(false)]
public int EmpId { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(100,MinimumLength=3)]
public String EmpName { get; set; }
[Required(ErrorMessage = "Employee Address is required")]
[StringLength(300)]
public string Address { get; set; }
[Required(ErrorMessage = "Salary is required")]
[Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
public int Salary{ get; set; }
[Required(ErrorMessage = "Please enter your email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[MaxLength(50)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
public string Email { get; set; }
}
}