How to create a static dropdown in Razor syntax?
Asked Answered
F

3

17

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.

Faison answered 2/6, 2015 at 20:50 Comment(6)
You don't have to use the DropDownList helper... In fact, if it's just the three options you have I'd just write it out like you have.Gans
:-) Yes, I know. But.... building blocks. I'm trying to start with the simple method, and then go from there. For reasons I didn't explain in the question, I'd like to know how to do this,Faison
Instead of var model = dbContext.Todos.ToList() write var model = new List<Todo> { new Todo(), new Todo() }...Spiritless
/\ did you mean to leave that comment on this thread?Faison
I did. You claim you can make a working dropdownlist with entries that come from a database. Using very simple code you can, instead of reading entries from a database, instantiate a simple List<T> that provides your dropdown with data. Of course, as my comment also indicates though less obviously so, we have no idea what code you do have and what specific functionality you need replaced.Spiritless
Ok, I guess I wasn't clear. I did NOT mean to imply that I can make a working dropdownlist with entries that come from a database. I only meant to say that all the tutorials I've found use this method. 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.Faison
Y
40

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"))
Yokoyokohama answered 2/6, 2015 at 21:4 Comment(6)
Excellent! Thank you!! Yes that is EXACTLY what I am looking for! Now, Brandon, could I ask you to leave your original answer in tack, but then also show underneath it, how to, as you said, do this the best-practice way?Faison
Brandon O'Dell. You, sir, have just saved me many hours of frustration. Thank you.Faison
Glad I was able to help you out. Cheers!Acie
Now can someone explain why that's better than just putting a <select> in the cshtml? To me, this accomplishes nothing other than requiring a recompilation to add an option. But I'm probably missing something.Lucia
@Lucia - It's useful if you want values to be strongly typed. Let's say you have an enum that represents Status of a record (Pending, Published, Deleted). You could have a single method in your code to enumerate the enum values and build the options. If you want to add a status later down the road you can do so easily. This approach also works well for keeping code "DRY". If you have multiple places where you display the same select list, you can build the list in code in a single place, then reference that in all of your views.Acie
@BrandonO'Dell Thanks for the response, good points. But if you don't need to use this list in multiple places, it's still simpler to just use a select. I think people become enslaved to "the way the framework does it" and refuse to acknowledge that sometimes it's just more complicated than it's worth. Or that simpler is better.Lucia
G
3

Have a look at the docs for this overload

public static MvcHtmlString DropDownList(
  this HtmlHelper htmlHelper,
  string name,
  IEnumerable<SelectListItem> selectList
)

So just add a reference to your List<SelectListItem>() with your options.

List<SelectListItem> items = new List<SelectListItem>();
 items.Add(new SelectListItem { Text = "Option1", Value = "Option1"});
 items.Add(new SelectListItem { Text = "Option2", Value = "Option2" });
 items.Add(new SelectListItem { Text = "Option3", Value = "Option3", Selected = true });

You can even embed that in your view if you don't want to pass it from your controller.

@{
    List<SelectListItem> items = ...
}

Then use it

@Html.DropDownList("FooBarDropDown", items)
Gans answered 2/6, 2015 at 21:5 Comment(2)
Thanks Jasen! I REALLY appreciate it. However, I'm not getting this to work. I get this error at runtime: Compiler Error Message: CS0103: The name 'items' does not exist in the current context". I added "List<SelectListItem> items = ..." to the controller in the [HttpGet] ActionResult. Wrong place? What am I missing?Faison
If you passed the list from the controller and are using @model List<SelectListItem> then it would be @Html.DropDownList("FooBarDropDown", Model).Gans
J
0

You can initialize a SelectListItem list (done here directly in the view) and then pass it to the DropDownList helper:

@{         
    List<SelectListItem> Listitems = new List<SelectListItem>();
    for(int i = 1; i <= 50; i++)
    {
       items.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
    }
 }

 @Html.DropDownList("ddlSequence", Listitems , new { id = "ddlSequence", @class = "form-control" })
     
Jillene answered 27/9, 2020 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.