DropDownList in MVC 4 with Razor

C#asp.net MvcRazor

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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

     

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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

Solution 9 - C#

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>

Solution 10 - C#

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

Solution 11 - C#

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>

Solution 12 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2232273View Question on Stackoverflow
Solution 1 - C#chridamView Answer on Stackoverflow
Solution 2 - C#john PeraltaView Answer on Stackoverflow
Solution 3 - C#Gabriel SimasView Answer on Stackoverflow
Solution 4 - C#shuvo sarkerView Answer on Stackoverflow
Solution 5 - C#AymanView Answer on Stackoverflow
Solution 6 - C#Basheer AL-MOMANIView Answer on Stackoverflow
Solution 7 - C#Bryan LegendView Answer on Stackoverflow
Solution 8 - C#RameshblView Answer on Stackoverflow
Solution 9 - C#Bryan LegendView Answer on Stackoverflow
Solution 10 - C#Jeetendra NegiView Answer on Stackoverflow
Solution 11 - C#mut tonyView Answer on Stackoverflow
Solution 12 - C#Muhafil SaiyedView Answer on Stackoverflow