验证ASP.NET MVC中的基元类型

时间:2010-05-29 20:39:01

标签: asp.net-mvc

我已经实现了以下类来验证数据

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");
    }
}

效果很好!提交表单时我只是做

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

但我还需要验证Age是一个整数

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

如何将此移至我的模型?

1 个答案:

答案 0 :(得分:1)

ASP.NET MVC中的模型绑定会自动执行这些验证(确切地说,它被视为模型绑定错误)。请仔细阅读:http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html