How to create a static dropdown in Razor syntax?
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)
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"))