0

Ok I've looked around at different websites regarding the use of ENUM in DropDownLists and am a little confused with people using Custom Helpers to pass values into a ViewBag before passing them to the DDL.

http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

enum values in drop down list in mvc4

http://webcache.googleusercontent.com/search?q=cache:http://www.ninjanye.co.uk/2012/01/creating-dropdown-list-from-enum-in.html

I've used various Html.DropDownList helpers throughout the website but have not used to ENUM in a DDL before. I'd rather not hardcode them into the View as I am using a switch statement to control what occurs when a filter option is selected. So was wondering if there was a simple way of implementing this without creating a new helper to remedy the situation.

Here is what I have so far (minus unnecessary code):

public enum OrderFilter
{
  All,
  Live,
  InProgress,
  Invoiced,
  Outstanding
}

public ActionResult Index(OrderFilter? orderFilter)
{
  ViewBag.FilterOptions = orderFilter;
}

@Html.DropDownList("orderFilter", (IEnumerable<SelectListItem>)ViewBag.FilterOptions, "Filter Options")

If I do it as I have done above, the response is "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'orderFilter'".

I am looking for something similar to the following code, but without the use of a custom helper (if possible).

@Html.DropDownList("misc", (IEnumerable<SelectListItem>)ViewBag.Misc)

var users = _userRepository.GetData().Select(u => new SelectListItem
  {
    Value = u.Id.ToString(CultureInfo.InvariantCulture),
    Text = u.Details
  });

 ViewBag.Administrators = users;
Community
  • 1
  • 1
Damian
  • 574
  • 1
  • 6
  • 19
  • Why wouldn't you want a custom html helper for this? – Henk Mollema Sep 24 '13 at 12:21
  • I've done all the other dropdownlists (which don't use ENUM) with the built in functionality provided by MVC. So I am trying to avoid creating excess code where it might not be needed. I am completely open to suggestion, if you can provide valid reasoning why it should be used then I will be happen to test it. – Damian Sep 24 '13 at 12:27

1 Answers1

0

After extensive investigation into this matter, it's not a simple task doing it the way I wanted. So I have added in the helper class to handle ENUM values within a dropdown list.

Some of the examples I've looked at use models in conjunction with the ENUM Helper but as I don't need that I found the below video tutorials fairly useful. The below videos are the current implementation I have and it works as I expected.

Binding Enum type with Dropdownlist Part 1

Binding Enum type with Dropdownlist Part 2

Binding Enum type with Dropdownlist Part 3

Damian
  • 574
  • 1
  • 6
  • 19