In any case, for the mvc-framework to confirm my action parameter, as well as ModelState.IsValid

I have an action and you want to do some simple param check

ActionResult Test([Range(0,10)] int i) { // ModelState.IsValid is always true, i want it to be false if i > 10 or i < 0 } 

in any case, fix it or get around it or any alternatives provided by MVC?

+4
source share
3 answers

I thought to just check the definition of the data annotation attribute before giving you some alternatives. I was surprised to see that AttributeUsage defined in such a way that you can also apply to the parameters of the method, and, unfortunately, it did not work, since I tried myself. Although I'm not sure why they allowed this parameter to the method parameters (I see it as valid, but it doesn’t work)

As for alternatives, you can try this,

 public ActionResult Test(int i) { var rangeAttr = new RangeAttribute(0, 10); if(!rangeAttr.IsValid(i)) ModelState.AddModelError(i.ToString(), rangeAttr.FormatErrorMessage("i")); } 
+2
source

Well in mvc the most appropriate way to do this in your model is to just put the attribute

  [Range(0,10)] public int yourproperty{ get; set; } 

read this http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-6

0
source

You can create your own error if it is outside this range, and this will make IsValid false.

So for example, you could do something like

  if(i < 0 || i > 10) ModelState.AddModelError("Range", "Invalid Range"); 

I believe this should work.

0
source

All Articles