开发者

ASP.NET MVC 2 validation LINQ to SQL

开发者 https://www.devze.com 2022-12-24 08:37 出处:网络
Currently I have a DataModel object which contains my linq to sql classes(a dmbl file). Currently I use a partial class to validate the incoming input. For example

Currently I have a DataModel object which contains my linq to sql classes(a dmbl file). Currently I use a partial class to validate the incoming input. For example

public partial class User : IEntity
{

    public NameValueCollection CheckModel()
    {
        return GetRuleViolations();
    }

    /// <summary>
    /// Method validates incoming data, by given rules in the if statement.
    /// </summary>
    /// <returns>NameValueCollection</return开发者_如何学编程s>
    private NameValueCollection GetRuleViolations()
    {
        NameValueCollection errors = new NameValueCollection();
        if (string.IsNullOrEmpty(Username))
            errors.Add("Username", "A username is required");
        // and so on
        return errors;
    }

}

Now what I want to try to do is add validation attributes to the fields. For example I want to try to add the required attribute to the field Username instead/in addtion of using the validation I currently have. My question is how can I achieve this because the dmbl file is auto generated. Or maybe it is not possible and should I use a different approach?


You should read about Metadata classes. This is example blog entry about it.

Adding Required atrribute to User class will be something like:

[MetadataType(typeof(UserMetadata))]
public partial class User
{
}

public class UserMetadata
{
    [Required]
    public string Username { get; set; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号