开发者

ValidateModel Problem with DataAnnotations

I have a SearchViewModel with these properties:

    [RegularExpression("name")]
    public String SortField;

    [RegularExpression("asc|desc")]
    public String SortDirection;

As you can see, I want "name" to be 开发者_如何学Pythonthe only valid value of SortField at this time, and "asc" or "desc" the only valid values for SortDirection.

However, ValidateModel isn't catching any error when the values are different, and ModelState.IsValid returns true. Basically I can supply any value and it will always go through.

The abbreviated controller method:

    public ActionResult List(SearchViewModel model)
    {            
        ValidateModel(model); // No error here
        Boolean isValid = ModelState.IsValid // This is true

        //...
    }

What am I doing wrong?

Edit: I'm not sure if this is important, but I'm using a custom ModelBinder.


Those aren't properties; they're fields. Binding and validation only work against properties.

FYI - [RegularExpression] also allows the user to specify no value for the input (which gets converted to a null). If you want to disallow null values, use [Required] in addition to [RegularExpression].

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜