3

我当前的 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属性。

4

2 回答 2

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
    */
}
于 2012-05-06T21:23:59.900 回答
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";
        }
    }
}
于 2012-05-06T21:41:17.273 回答