Nyprez Nyprez - 2 months ago 11
ASP.NET (C#) Question

MVC - Show list of strings in DropDownList

Based on this code (auto-generated Control/View code from Visual Studio):

<div class="form-group">
@Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*Comment: Want to replace EditorFor to DropDownList("Banana, "Apple", "Orange"*@
@Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
</div>
</div>


I would like to add something similar like:

@Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" })


(also auto-generated code, but for
UserId
) instead of
@html.EditorFor...


I was able to see list of
UserName
(value =
Id
) from db via Controller:

ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", Test.UserId);


Now, I don't want that ViewBag read from database, instead I want it to list 3 different strings that I will use to let user to chose for indata(meaning, limit them to choice one of these 3 string instead writing it).

Strings I want it to list:


  • "Banana"

  • "Apple"

  • "Orange"



How do I do that?

Answer

Try this,

@Html.DropDownList("DropDown", new List<SelectListItem>
                                 { new SelectListItem { Text = "Banana", Value = "1", Selected=true},
                                   new SelectListItem { Text = "Apple", Value = "2"},
                                   new SelectListItem { Text = "Orange", Value = "3"}
                                   }, "Select Fruit")

OR

Get value in model

@Html.DropDownListFor(x => x.Id, new List<SelectListItem>
                                 { new SelectListItem { Text = "Banana", Value = "1", Selected=true},
                                   new SelectListItem { Text = "Apple", Value = "2"},
                                   new SelectListItem { Text = "Orange", Value = "3"}
                                   }, "Select Fruit")