I need a dropdown list on my page that will allow a user to select their state. Since this is probably a control that will be used elsewhere, I thought it would be a good idea to create an MVC View User Control that could be reused.
I was thinking the control would look something like this:
<select name='' id=''> <option value='AL'>Alabama</option> <option value='AK'>Alaska</option> </select>
And the code in my view would be something like:
<%= Html.RenderPartial('StateDropdownControl') %>
My question is, what’s the best way to set the name and id on the control? I’d want to make sure I could have multiple instances of this control on one page, if needed. Also, I’d want to be able to send in the state that should be selected by default.
Would I do it with ViewData somehow?
Corey is on to the right solution. I think declaring specific Model objects for your view makes the views VERY simple and as a side bonus makes them dirt easy to test.
So instead of just passing the ID as the object, you’d probably want to create your own Model object to pass in.
It could look something like this:
Obviously, keep adding whatever you need to this model to make your view correct.
Then, you could call it like this:
Then just make sure you put in checks for things like ID being null/blank (that should probably throw an error) and SelectedState being null/blank.