MVC3 validation with data-annotation?

别说谁变了你拦得住时间么 提交于 2019-12-04 19:23:21

Something like:

[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
public int Value { get; set; }

Making a drop-down list required does not make sense. What you want required is that the user pick a value other than zero from the drop-down list. So what should be required is the SelectedAccount property. You should use the MVC helper method to bind the drop-down selected value to the SelectedAccount property:

@Html.DropdownListFor(m => m.SelectedAccount, new SelectList(Model.Accounts))

I am probably off on the syntax but you can look that up.

Now with regards to your other issue of ensuring that the value is not zero. Is the account number represented as a number or can it contain non-numeric characters? If it is a number then you should represent it as such in your code. And if it is truly a string, then the first value of your drop-down list should be an empty string and not zero.

If you decide that it is a number, then use the Range annotation to ensure that the value is greater than zero:

[Required]
[Range(1, Int32.MaxValue)]
public string SelectedAccountNumber {get;set;} 

Hope that helps!

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