Search code examples
asp.net-mvchtml.dropdownlistfor

How to create a static dropdown in Razor syntax?


After hours of looking on Google and Stack Overflow, I can not find one bloody example of how to build a totally brain dead simple dropdown list that does not come from a database. Honestly, I am having a hard time getting my head around MVC. Can someone please show me how to create this:

<select name="FooBarDropDown" id="FooBarDropDown">
    <option value="Option1" selected>This is Option 1</option>
    <option value="Option2">This is Option 2</option>
    <option value="Option3">This is Option 3</option>
</select>

Using this:

@Html.DropDownList....

I am looking for an all-in-one-line solution... all in the view. I am having a devil of a time with the syntax.


Solution

  • I think this is what you are looking for. It would be best though to refactor list construction into view model or in controller.

    @Html.DropDownList("FooBarDropDown", new List<SelectListItem>
    {
        new SelectListItem{ Text="Option 1", Value = "1" },
        new SelectListItem{ Text="Option 2", Value = "2" },
        new SelectListItem{ Text="Option 3", Value = "3" },
     }) 
    

    An an example of placing this in the controller might look like this:

    public ActionResult ExampleView()
    {
        var list = new List<SelectListItem>
        {
            new SelectListItem{ Text="Option 1", Value = "1" },
            new SelectListItem{ Text="Option 2", Value = "2" },
            new SelectListItem{ Text="Option 3", Value = "3", Selected = true },
        }; 
    
        ViewData["foorBarList"] = list;
        return View();
    }
    

    And then in your view:

    @Html.DropDownList("fooBarDropDown", ViewData["list"] as List<SelectListItem>)
    

    If this is truly a static list that you might have to reuse in other views / controllers, then I would consider putting this logic into a static class of sorts. Example:

    public static class DropDownListUtility
    {   
        public static IEnumerable<SelectListItem> GetFooBarDropDown(object selectedValue)
        {
            return new List<SelectListItem>
            {
                new SelectListItem{ Text="Option 1", Value = "1", Selected = "1" == selectedValue.ToString()},
                new SelectListItem{ Text="Option 2", Value = "2", Selected = "2" == selectedValue.ToString()},
                new SelectListItem{ Text="Option 3", Value = "3", Selected = "3" == selectedValue.ToString()},
            };             
        }
    

    Which then leaves you a few different ways of accessing the list.

    Controller Example:

    public ActionResult ExampleView()
    {
        var list = DropDownListUtility.GetFooBarDropDown("2"); //select second option by default;
        ViewData["foorBarList"] = list;
        return View();
    }
    

    View Example:

    @Html.DropDownList("fooBarDropDown", DropDownListUtility.GetFooBarDropDown("2"))