开发者

ASP.NET MVC 2 Validate SelectList

开发者 https://www.devze.com 2023-01-12 00:54 出处:网络
Let\'s say I have the following selectlist (Countries) in a ViewModel: //.. private static string[] _countries = new[] {

Let's say I have the following selectlist (Countries) in a ViewModel:

//..
private static string[] _countries = new[] {
"USA",
"Canada",
"Japan"
};
//...
SelectList Countries = new SelectList(_countries, dinner.Country);
//...

And I render a dropdown list in the following fashion:

<%: Html.DropDownListFor(m => m.Dinner.Country, Model.Countries) %>

I noticed that using firebug, I can inject my own values into the DropDownList and that value may be inserted into th开发者_JAVA百科e database.

What is the best way to validate that there are no injected values (preferably a DRY method)?


I would recommend taking advantage of DataAnnotations and create your own custom validation attribute.

This provides a way to encapsulate your validation logic (satisfying your DRY requirement), and will be applied server-side (preventing html manipulations like the one you described).


You should always validate your data server side anyways before inserting in the DB. If you had a key constraint it wouldn't be such an issue because the update or insert would fail. In this case though you should have a server side business rule to validate your object before doing the SQL call.

Since your building a list from a static list of items, the list should be available to your business layer so that you can compare against it to make sure that the value contained in your model is valid. You can add a method to your object such as IsValid or something that would do a quick validation and check that the values do exist for these hard coded selections.

0

精彩评论

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