Question

I'm trying to create a client-side validated dropdown list in an MVC4 application using the Razor view engine.

The code in the view to generate the dropdown list is as follows:

 @Html.DropDownList("Test", new SelectList(ViewBag.AvailableLoBsDescriptions, ViewBag.AvailableLoBsIds), "--none--")

Note that ViewBag.AvailableLoBsDescriptions is created in the controller using an IList while ViewBag.AvailableLoBsIds is also created in the controller using an IList.

What I expected to happen is have Razor generate a dropdown menu where Descriptions populates the inner html of each while the Ids populates the value="...". However, there is nothing generated for value at all, resulting in something like this:

<select id="Test" name="Test"><option value="">--none--</option>
<option>N/A</option>
<option>aaaa</option>
<option>bbbb</option>
<option>cccc</option>
<option>dddd</option>
<option>eeee</option>
<option>ffff</option>
</select>

Looking at the SelectList documentation, http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.108%29.aspx, it seems to me that this should work. Does anyone have an idea why the values are not being generated for anything other than the placeholder?

Thanks!

Was it helpful?

Solution

The constructor you are using looks like the following:

SelectList(IEnumerable, Object)

The second parameter here dictates the currently selected object from the collection in the first parameter. It does not dictate an object to use as a list of values.

What you should be doing is using SelectList(IEnumerable, String, String). This allows you to pass the name of a property (of each element of IEnumerable) to use for the description and one for the value. You can then produce something like this:

Controller:

// Create your IEnumerable
var LoBs = new List<LoB>();

// Assign some parameters to your objects
var exampleItem = new LoB();
exampleItem.Description = "Option text";
exampleItem.Value = "myValue";

// Populate your list and return your view.
LoBs.Add(exampleItem);
ViewBag.LoBs = LoBs;
return View();

View:

@Html.DropDownList("Test",
    new SelectList(ViewBag.LoBs, "Value", "Description"),
    "--none--")

Et voila...

<select id="Test" name="Test">
    <option value="">--none--</option>
    <option value="myValue">Option text</option>
</select>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top