asp.net mvc int property bind exception

牧云@^-^@ 提交于 2019-12-22 18:47:35

问题


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.

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3451255/asp-net-mvc-int-property-bind-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!