ASP.NET MVC: MultiSelectListBox without selection

Alright, now that was one hell of a mystery. For some odd reason my MultiSelectListBox didn’t show the selected items like it should.


The case was very simple, and easily reproducible too. Start of in VS2008 with a new MVC Web Application, open up the HomeController class and change it’s code to this (only italic code was added):


    public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";

var dic = new Dictionary<string, string>();
dic.Add("1", "First thing");
dic.Add("2", "Second thing");
dic.Add("3", "Third thing");

var sel = new ArrayList();
sel.Add("2");

ViewData["multiselect"] = new MultiSelectList( dic, "Key", "Value", sel);

return View();
}

public ActionResult About()
{
return View();
}
}

As you can see, this adds a MultiSelectList to the ViewData object. It conatins a dictionary with 3 items. In addition an ArrayList with 1 string is passed, to represent the selected items. Now, open up Home\Index.aspx and add the following code somewhere in the HTML-Body:


<%= Html.ListBox("multiselect", ViewData["multiselect"] as MultiSelectList)%>

When running the application I expect the homepage to show up with the second item in the select list selected, but in stead it showsno selection at all:


image


It took quite some puzzling, but it the problem turned out to be caused by the element in ViewData having the same name as the Id for the control. If you change the line in Home\Index.aspx as follows:


<%= Html.ListBox("someMultiselect", ViewData["multiselect"] as MultiSelectList)%>

The selection will finally show:


image


Pfff, glad I nailed that one…

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>