Well, I have a version of Jquery for Choice applied to the select that displays correctly on my page, and I did this with the following code. First I have a BaseController that sets the ViewBag property, listing all possible categories:
protected override void OnActionExecuted(ActionExecutedContext filterContext) { try { _connection.Open(); this.ViewBag.AvailableCategories = new MultiSelectList(_connection.Query<Category>("select * from Category"), "CategoryID", "Name"); } catch (Exception ex) { throw new HttpException(500, ex.Message); } finally { _connection.Close(); } base.OnActionExecuted(filterContext); }
Further, when navigating through /Event/View/1 , I have the EventController setting ( NOTE , this controller bases the above controller) with the following View method.
public ActionResult View(int id) { Event evt = null; try { evt = Event.Where(_connection, id); if (evt == null) { throw new HttpException(404, "Oops! The event you're looking for does not exist."); } } catch (Exception ex) { throw new HttpException(500, ex.Message); } return View(evt); }
He sets the model, as you can see, in the next model.
public class Event { public int EventID { get; set; } public int BusinessID { get; set; } public string Name { get; set; } public string Description { get; set; } public int NeighborhoodID { get; set; } public IEnumerable<int> CategoryIds { get { if (Categories == null) { return new List<int>(); } return Categories.Select(c => c.CategoryID).AsEnumerable(); } } public List<EventCategory> Categories { get; set; } public List<EventHours> Hours { get; set; } public static Event Where(IDbConnection connection, int id) { Event result = null; try { connection.Open(); var sql = @" select * from Event where EventID = @EventID select * from EventCategory where EventID = @EventID select * from EventHours where EventID = @EventID"; using (var multiResult = connection.QueryMultiple(sql, new { EventID = id })) { result = multiResult.Read<Event>().FirstOrDefault(); if (result != null) { result.Categories = multiResult.Read<EventCategory>().ToList(); result.Hours = multiResult.Read<EventHours>().ToList(); } } } finally { connection.Close(); } return result; } }
Finally, I have the following markup in the view.
@Html.DropDownListFor(m => m.CategoryIds, ViewBag.AvailableCategories as MultiSelectList, new { multiple = "multiple", @class = "chzn-container" })
Now, as I said, it displays correctly and lists all categories as expected. However, despite the fact that the CategoryIds property does display two selected categories, it does not set them (or show them for that matter), as it was selected in the Selected folder at boot time.
I am forced to assume only that if the user selects a value from the drop-down list that will not be attached to the message correctly, or because he does not change the HTML when he selects an element.
So my question is, is it right for two-way data to communicate with a dropdown in MVC?