开发者

Validating primitive types in ASP.NET MVC

开发者 https://www.devze.com 2023-01-01 06:50 出处:网络
I\'ve implemented the following classes to validate data public abstract class Validated { public bool IsValid { get { return (GetRuleViolations().Count() == 0); } }

I've implemented the following classes to validate data

public abstract class Validated
{
    public bool IsValid { get { return (GetRuleViolations().Count() == 0); } }

    public abstract IEnumerable<RuleViolation> GetRuleViolations();
}

public partial class User: Validated
{
    public override IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (this.Age < 1)
            yield return new RuleViolation("Age can't be less than 1");
    }
}

It works great! When the form is submitted 开发者_Go百科I just do

if (user.IsValid == false) blah...

But I still need to validate that the Age is an integer

int a = 0;
if (!int.TryParse(age, out a))
{
            error = "Not integer";
            // ...
}

How can I move this to my model?


Model binding in ASP.NET MVC does those kind of validation automatic (to be exact its being considere as model-binding errors). Please read very carefully through this: http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

0

精彩评论

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

关注公众号