This is my first question, and it is probably bad, so please be careful.
While working on my first ASP.Net MVC2 web application recently, I ran into some problems when I needed to select multiple values ββfrom a list. I worked on it using some jQuery, but went ahead and put together a very simple code for demonstration. I use EF for a model with two objects - Clients and HelpDeskCalls:
Controller:
public ActionResult Edit(int id) { Customer currCustomer = ctx.Customers.Include("HelpDeskCalls").Where(c => c.ID == id).FirstOrDefault(); List<HelpDeskCall> currCustCalls = (ctx.HelpDeskCalls.Where(h => h.CustomerID == id)).ToList(); List<SelectListItem> currSelectItems = new List<SelectListItem>(); List<String> selectedValues = new List<string>(); foreach (HelpDeskCall currCall in currCustCalls) { bool isSelected = (currCall.ID % 2 == 0) ? true : false;
View:
<div class="editor-field"> <%: Html.ListBoxFor(model => model.HelpDeskCalls, new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable) ViewData["currSelected"]), new { size = "12" })%> <%: Html.ListBoxFor(model => model.HelpDeskCalls, ViewData["currCalls"] as IEnumerable<SelectListItem>, new { size = "12"}) %> <%: Html.ListBox("Model.HelpDeskCalls", new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable)ViewData["currSelected"]), new { size = "12"}) %> <%: Html.ValidationMessageFor(model => model.HelpDeskCalls) %> </div>
For this example, I simply select HelpDeskCall.ID, which are even. I am trying to use two different syntax for ListBoxFor: One uses IEnumerable values ββto select, using IEnumerable from SelectListItems. By default, when I run this code, the ListBoxFor are not selected, but the non-strongly typed ListBox selects correctly.
I read this post on ASP.Net and this thread on SO, but no joy. In fact, if I add an override of ToString () to my HelpDeskCall class (as suggested in the ASP.net stream), all values ββwill be selected, which is also not true.
If someone can shed light on how this should work (and what I am missing or doing wrong), this neophyte would be very grateful.
John
asp.net-mvc asp.net-mvc-2
JohnMc0831 Jul 07 '10 at 11:15 2010-07-07 11:15
source share