views:

50

answers:

2

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 the database.

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

+1  A: 

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.

Kelsey
+1  A: 

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).

MJ Richardson
Thanks, this is the kind of answer I was looking for. MVC 2 specific (annotations) rather than general (boolean methods).
npsken