Html.dropdownlist with static content

23,566

Solution 1

Your first option is to include the html within your view:

<select id="selection">
    <option>Exact match</option>
    <option>Starts with</option>
</select>

Second option is to use a hard-coded built in html helper:

@Html.DropDownList("selection", new List<SelectListItem>() {new SelectListItem { Text="Exact match", Value = "Match"}, new SelectListItem { Text="Starts With", Value = "Starts"}})

The third option which I would prefer if it is used a lot on your site is to create an html helper extension and you can simply use it like this:

@Html.SearchSelectionList()

Here is the code for this:

public static MvcHtmlString SearchSelectionList(this HtmlHelper htmlHelper)
{
    return htmlHelper.DropDownList("selection", new List<SelectListItem>() { new SelectListItem { Text = "Exact match", Value = "Match" }, new SelectListItem { Text = "Starts With", Value = "Starts" } });
}

Solution 2

Why do you need the HTML-helper when only using static data?

<select id="myDropDownList" name="myDropDownList">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Or this perhaps:

@{
var list = new SelectList(new []
    {
        new {ID="1", Name="volvo"},
        new {ID="2", Name="saab"},
        new {ID="3", Name="mercedes"},
        new {ID="4", Name="audi"},
    },
    "ID", "Name", 1);
}
@Html.DropDownList("list", list)

Solution 3

you can refer this Bind Dropdownlist In Mvc4 Razor

Let's try this way also

public static class DDLHelper
{
    public static IList<SelectListItem> GetGender()
    {
        IList<SelectListItem> _result = new List<SelectListItem>();
        _result.Add(new SelectListItem { Value = "2", Text = "Male" });
        _result.Add(new SelectListItem { Value = "1", Text = "Female" });
        return _result;
    }
}

Now call static class in Controller

public ActionResult Index()
{

    ViewBag.Gender = new SelectList(DDLHelper.GetGender(), "Value", "Text");
    return View();
}

In last now ViewBag call in view

@Html.DropDownList("gender", new SelectList(ViewBag.Gender, "Value", "Text"), "--Select--")
Share:
23,566

Related videos on Youtube

john Gu
Author by

john Gu

Updated on November 29, 2020

Comments

  • john Gu
    john Gu over 3 years

    I am working on an asp.net mvc web application , and on my advance search page i want to have three html.dropdownlist which contain static values:-

    1. Exact match

    2. Start With

    and i need the dropdownlists to be beside any of the search field.

    so can any one advice how i can create such static html.dropdownlist, as all the current dropdownlists which i have are bing populated with dynamic data from my model ?

    Thanks