开发者

asp.net mvc int property bind exception

I have a int property in my class and want to validate if the user has entered a string. How can I do that using data annotations? When I pass a non-integer value I get a excpetion like this:

The 开发者_如何学编程value 'asdasd' is not valid for property.

For example using this validation attribute:

[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }

and entering 'aaa' in a field tha uses the model I've got an excepetion with this message:

The value 'aaa' is not valid for Number.

Instead of the "Invalid Number" message.

Any Ideas?


I've put

[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }

but I've got this message from an excpetion

The value 'aaa' is not valid for Number.


There are two stages of validation at play here.

Before the validation set up in your attributes is called, the framework first attempts to parse the information.

So here are a couple of examples based on this code:

[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }

I type nothing into the box...

"Invalid Number" (Framework will create a null integer, your validation rule fails)

I type "A" into the box...

"The value 'A' is not valid for Number." (Framework cannot convert "A" into a nullable int, so the framework validation rule fails and your validation rule it not checked.

** Solutions **

1 - Live with the default message until you are using MVC 3 / .NET 4, which makes it easier to override these messages

2 - Exclude the value from the binder, so it won't cause an error (but you will have to bind it and check it yourself)

[Bind(Exclude="MyNumber")]

3 - Make it a string on the model, then test it with a TryParse and add your own custom model error (This is a reasonable practice and reminds us all why View Models are used rather than Domain Objects!)

if (!Int32.TryParse("MyNumber", out myInteger)) {
    ModelState.AddModelError("MyNumber", "That isn't a number!");
}

There are actually lots of solutions, but I would say go with option 3 for now.


You could put a Range-attribute on your model-field like so:

[Range(0, 9999)]
public int Something {get; set;}

Now whenever the user inputs a string it will not validate, and also the int must be between 0-9999

this should also work with

[Range(0, 9999)]
public string Something {get; set;}

and

[Range(0, 9999)]
public object Something {get; set;}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜