148

I'm trying to create a DropDownList on a razor view.

Would someone help me with this?

Normal HTML5 code:

<select id="dropdowntipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>

I tried this:

@{
    var listItems = new List<ListItem> { 
        new ListItem { Text = "Exemplo1", Value = "Exemplo1" }, 
        new ListItem { Text = "Exemplo2", Value = "Exemplo2" }, 
        new ListItem { Text = "Exemplo3", Value = "Exemplo3" } 
    };
}

@Html.DropDownListFor(model => 
    model.tipo, 
    new SelectList(listItems), 
    "-- Select Status --"
)
dey.shin
  • 990
  • 10
  • 21
user2232273
  • 4,898
  • 15
  • 49
  • 75
  • 7
    your `var listItems = ...` should be in your controller not your View. – Liam Jul 18 '13 at 15:15
  • 1
    this is MVC3 but it's the same syntax as MVC4: http://stackoverflow.com/questions/5070762/mvc3-razor-html-dropdownlistfor – Liam Jul 18 '13 at 15:18
  • 2
    @Liam: It probably belongs in the view model, not in the controller. The controller shouldn't have a dependency on `ListItem` as it's a UI-bound concept. It shouldn't even _really_ be in the view model, just in the view. The controller should build the view model, the view model should contain the data, the view should build UI elements (like `ListItem`) to that data. – David Jul 18 '13 at 15:20
  • also try [this one](http://lesson8.blogspot.com/2013/06/bind-dropdownlist-in-mvc4-razor.html) – Sender Oct 03 '13 at 16:08
  • 2
    What is the value of using Razor over native HTML; Is it performance or functionality? Since no data is being pulled from the controller. – Barry MSIH Nov 15 '14 at 18:03
  • possible duplicate of [How to generate dropdownlist in asp.net MVC razor](http://stackoverflow.com/questions/16099258/how-to-generate-dropdownlist-in-asp-net-mvc-razor) – Farshid Shekari Jun 23 '15 at 19:46
  • I suggest you take a look at this http://stackoverflow.com/questions/18382311/populating-a-razor-dropdownlist-from-a-listobject-in-mvc – Sr.PEDRO Nov 16 '16 at 02:41
  • 1
    Someone please tell me what the model.tipo property represents, in a generic sense. –  Jun 05 '17 at 14:40
  • 1
    On the last line - How do you know what model to call? Where does "tipo" come from? – Andre Feb 02 '18 at 10:38
  • user4234032 - model.tipo is the property on the model class that will store the selected value of the drop down list. In this example the value for the drop down list is a string so tipo will most likely be a string property. public string tipo {get; set; } – jcrawfor74 Oct 12 '19 at 13:53

13 Answers13

258
@{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {
          Text = "Exemplo1",
          Value = "Exemplo1"
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo2",
            Value = "Exemplo2",
            Selected = true
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo3",
            Value = "Exemplo3"
        });
}

@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 2
    If you defined the List in controller, Then you need in View to cast it , like this: @Html.DropDownListFor(model => model.model_year, ViewBag.Years as List, "-- Select Year --") – Bashar Abu Shamaa Feb 26 '16 at 19:23
  • 4
    On the last line - How do you know what model to call? Where does "tipo" come from? – Andre Feb 02 '18 at 10:38
  • 3
    @Andre It's the name of model property. He read it from the question. The value binds to that field. – Hrvoje T Oct 10 '18 at 13:15
  • You have to be careful as none of the posted solutions perform any kind of server-side validation. Here's an elegant solution that performs both client-side and server-side validation to ensure valid data is posted to the model. https://stackoverflow.com/a/56185910/3960200 – Etienne Charland May 17 '19 at 12:01
  • Ur showing a list that has no relevance ur not setting it anywhere please tidy up code – c-sharp-and-swiftui-devni Oct 31 '21 at 11:33
73
@{var listItems = new List<ListItem>
    {
          new ListItem { Text = "Exemplo1", Value="Exemplo1" },
          new ListItem { Text = "Exemplo2", Value="Exemplo2" },
          new ListItem { Text = "Exemplo3", Value="Exemplo3" }
    };
    }
        @Html.DropDownList("Exemplo",new SelectList(listItems,"Value","Text"))
john Peralta
  • 771
  • 5
  • 3
  • For this example to work I added this using above this code segment. @using System.Web.UI.WebControls; – Badar Dec 03 '17 at 15:41
43

You can use this:

@Html.DropDownListFor(x => x.Tipo, new List<SelectListItem>
    {
                        new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                        new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                        new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}
    })  
Esraa_92
  • 1,558
  • 2
  • 21
  • 48
Gabriel Simas
  • 567
  • 9
  • 15
22

//ViewModel

public class RegisterViewModel
{

    public RegisterViewModel()
    {
        ActionsList = new List<SelectListItem>();
    }

    public IEnumerable<SelectListItem> ActionsList { get; set; }

    public string StudentGrade { get; set; }

  }

//Enum Class:

public enum GradeTypes
{
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

//Controller Action

 public ActionResult Student()
    {
RegisterViewModel vm = new RegisterViewModel();
IEnumerable<GradeTypes> actionTypes = Enum.GetValues(typeof(GradeTypes))
                                             .Cast<GradeTypes>();
        vm.ActionsList = from action in actionTypes
                         select new SelectListItem
                         {
                             Text = action.ToString(),
                             Value = action.ToString()
                         };
        return View(vm);
    }

//view Action

 <div class="form-group">
                                <label class="col-lg-2 control-label" for="hobies">Student Grade:</label>
                                <div class="col-lg-10">
                                   @Html.DropDownListFor(model => model.StudentGrade, Model.ActionsList, new { @class = "form-control" })
                                </div>
shuvo sarker
  • 881
  • 11
  • 20
11

Here is the easiest answer:

in your view only just add:

@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))

OR in your controller add:

var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
        ViewBag.ExemploList = exemploList;

and your view just add:

@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )

I learned this with Jess Chadwick

Ayman
  • 580
  • 9
  • 27
10

Believe me I have tried a lot of options to do that and I have answer here

but I always look for the best practice and the best way I know so far for both front-end and back-end developers is for loop (yes I'm not kidding)

Because when the front-end gives you the UI Pages with dummy data he also added classes and some inline styles on specific select option so its hard to deal with using HtmlHelper

Take look at this :

<select class="input-lg" style="">
    <option value="0" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    <option value="1">11</option>
    <option value="2">22</option>
    <option value="3">33</option>
    <option value="4">44</option>
</select>

this from the front-end developer so best solution is to use the for loop

fristly create or get your list of data from (...) in the Controller Action and put it in ViewModel, ViewBag or whatever

//This returns object that contain Items and TotalCount
ViewBag.MembershipList = await _membershipAppService.GetAllMemberships();

Secondly in the view do this simple for loop to populate the dropdownlist

<select class="input-lg" name="PrerequisiteMembershipId" id="PrerequisiteMembershipId">
    <option value="" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    @foreach (var item in ViewBag.MembershipList.Items)
    {
        <option value="@item.Id" @(Model.PrerequisiteMembershipId == item.Id ? "selected" : "")>
            @item.Name
        </option>
    }
</select>

in this way you will not break UI Design, and its simple , easy and more readable

hope this help you even if you did not used razor

boyukbas
  • 1,137
  • 16
  • 24
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
  • Thanks bro, Microsoft documentation says you can use asp-items="[yourListHere]" but I found when I tried that it didn't display anything at all. When I used a For Each loop it all displayed properly. – SendETHToThisAddress Oct 09 '20 at 00:42
8

Using an array would be a little more efficient than creating a list.

@Html.DropDownListFor(x => x.Tipo, new SelectListItem[]{
                new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}})
Bryan Legend
  • 6,790
  • 1
  • 59
  • 60
7
@{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
    {
      Text = "One",
      Value = "1"
    });
listItems.Add(new SelectListItem
    {
        Text = "Two",
        Value = "2",
    });
listItems.Add(new SelectListItem
    {
        Text = "Three",
        Value = "3"
    });
listItems.Add(new SelectListItem
{
   Text = "Four",
   Value = "4"
});
listItems.Add(new SelectListItem
{
   Text = "Five",
   Value = "5"
});
}
@Html.DropDownList("DDlDemo",new SelectList(listItems,"Value","Text"))

Refer:- Create drop down list in MVC 4 razor example

Ry-
  • 218,210
  • 55
  • 464
  • 476
Rameshbl
  • 101
  • 1
  • 2
4

If you're using ASP.net 5 (MVC 6) or later then you can use the new Tag Helpers for a very nice syntax:

<select asp-for="tipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>
Bryan Legend
  • 6,790
  • 1
  • 59
  • 60
  • 1
    Can you provide an example where the items are dynamic? For a static list no point to use tag helpers. And make one of the options selected. – user3285954 Nov 07 '15 at 18:17
  • The point is that it's data bound. It automatically selects the option that the variable is set to and it sets the variable when the form is submitted. To make the items dynamic, just do a razor foreach. – Bryan Legend Nov 08 '15 at 19:20
4

just use This

public ActionResult LoadCountries()
{
     List<SelectListItem> li = new List<SelectListItem>();
     li.Add(new SelectListItem { Text = "Select", Value = "0" });
     li.Add(new SelectListItem { Text = "India", Value = "1" });
     li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
     li.Add(new SelectListItem { Text = "China", Value = "3" });
     li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
     li.Add(new SelectListItem { Text = "USA", Value = "5" });
     li.Add(new SelectListItem { Text = "UK", Value = "6" });
     ViewData["country"] = li;
     return View();
}

and in View use following.

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

if you want to get data from Dataset and populate these data in a list box then use following code.

List<SelectListItem> li= new List<SelectListItem>();
for (int rows = 0; rows <= ds.Tables[0].Rows.Count - 1; rows++)
{
    li.Add(new SelectListItem { Text = ds.Tables[0].Rows[rows][1].ToString(), Value = ds.Tables[0].Rows[rows][0].ToString() });
}
ViewData["FeedBack"] = li;
return View();

and in view write following code.

@Html.DropDownList("FeedBack", ViewData["FeedBack"] as List<SelectListItem>)
Jeetendra Negi
  • 443
  • 3
  • 3
3

This can also be done like

@model IEnumerable<ItemList>

<select id="dropdowntipo">
    <option value="0">Select Item</option>
    
    @{
      foreach(var item in Model)
      {
        <option value= "@item.Value">@item.DisplayText</option>
      }
    }

</select>
mut tony
  • 357
  • 7
  • 9
0

List<tblstatu> status = new List<tblstatu>();
            status = psobj.getstatus();
            model.statuslist = status;
            model.statusid = status.Select(x => new SelectListItem
            {
                Value = x.StatusId.ToString(),
                Text = x.StatusName
            });


  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
Muhafil Saiyed
  • 230
  • 1
  • 20
0

For those using .NET Core MVC who stumbled across this:

If your model has an enum for the property, you can simply put:

<select asp-for="MyEnum" asp-items="Html.GetEnumSelectList<MyEnum>()"/>

see: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0#enum-binding

Hope this helps someone.

Dennis
  • 31
  • 9