[c#] DropDownList in MVC 4 with Razor

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 --"
)

This question is related to c# asp.net-mvc razor

The answer is


@{
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


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


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"}
    })  

_x000D_
_x000D_
List<tblstatu> status = new List<tblstatu>();_x000D_
            status = psobj.getstatus();_x000D_
            model.statuslist = status;_x000D_
            model.statusid = status.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.StatusId.ToString(),_x000D_
                Text = x.StatusName_x000D_
            });_x000D_
_x000D_
_x000D_
  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
_x000D_
_x000D_
_x000D_


This can also be done like

@model IEnumerable<ItemList>

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


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


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>)

//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>

@{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"))

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>

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"}})

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC