我当前的Web项目有一个管理界面,可以编辑用户的详细信息(不是真正的革命,我承认......)。该视图使用具有验证属性的用户的强类型模型:
public class UserPrototype
{
[Required]
[StringLength(50, MinimumLength = 4)]
public string Username { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string FirstName { get; set; }
[Required]
[StringLength(50, MinimumLength = 1]
public string LastName { get; set; }
[Required]
[StringLength(250, MinimumLength = 6]
public string Password { get; set; }
/*
And so on
*/
}
当用户更新时,我只想在数据库中更新那些实际已更改的字段。主要原因是密码字段 - 密码当然存储为哈希值,因此当用户被记录进行编辑时,在该字段中显示没有任何意义。但模型绑定器验证需要有效的密码。
那么,我仍然可以使用相同的类,但不知何故只验证那些提交为已更改的字段(我可以通过javascript完成)?我想避免重复UserPrototype
类只是为了删除Required
属性。
答案 0 :(得分:1)
使用继承,这样就不必重复了。
public class BaseUserPrototype
{
[Required]
[StringLength(50, MinimumLength = 4)]
public string Username { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string FirstName { get; set; }
[Required]
[StringLength(50, MinimumLength = 1]
public string LastName { get; set; }
/*
And so on
*/
}
public class NewUserPrototype: BaseUserPrototype
{
[Required]
[StringLength(250, MinimumLength = 6]
public string Password { get; set; }
/*
And so on
*/
}
public class EditUserPrototype: BaseUserPrototype
{
[StringLength(250, MinimumLength = 6]
public string Password { get; set; }
/*
And so on
*/
}
答案 1 :(得分:0)
您可以使用IDataErrorInfo接口; 以这种方式在您的实体上实现它:
public class Entity: IDataErrorInfo
{
// this is the dictionary of errors
private readonly Dictionary<string, string> _errors = new Dictionary<string, string>();
private string _password;
public string Password
{
get{return _password;}
set
{
// YOUR ACTUAL VALIDATION CODE HERE. IF THERE IS A VALIDATION ERROR - ADD IT TO THE DICTIONARY
if(string.IsNullOrEmpty(value))
_errors["Password"] = "Error with password field";
}
}
}