In a recent project that used .NET MVC, I had to change a simple Textbox display (with Model Binding) to a Dropdown with a static preset list of options. At first, I thought this would be relatively quick task to accomplish and a that a simple Google search would yield the results I was looking for. As it turns out I had to piece together information from a variety of sources to accomplish the task in this manner.
Here’s what I needed to do…..
-A select box populated with static options
-Bind the select box to a DB column to allow for…
-Display the value currently in the DB
-Save the selected value to the DB.
Here’s how I accomplished it…..
In my Controller, I added a List of SelectListItems to the ViewData so that I can access it in the view and still pass in the model and allow it to bind to the partial view.
PERSON person = null;
//Create a new list of SelectListItems
List<SelectListItem> items = new List<SelectListItem>();
//Get the person object
person = _personRepository.GetPersonById(id);
//Create the static list of values for the Dropdown
Text = “”,
Value = null
Text = “TRUE”,
Value = “1″
Text = “FALSE”,
Value = “0″,
//Assign the items SelectListItems
ViewData["items"] = items;
In my partial view I changed the TextBoxDisplayFor to a DropDownListFor, and added a reference to the ViewData items (with a cast). Here’s how it looks….
<%: Html.LabelFor(model => model.NAME) %>:
<%= Html.DropDownListFor(model => model.NAME, (IEnumerable<SelectListItem>)ViewData["items"]) %>