@Html.LabelFor(model => model.Category)
@Html.EditorFor(m...">

DropDownList in ASP.NET MVC 3

<div class="editor-label"> @Html.LabelFor(model => model.Category) </div> <div class="editor-field"> @Html.EditorFor(model => model.Category) @Html.ValidationMessageFor(model => model.Category) </div> 

This gives me a shortcut and text box. How can I get a dropdown with static selection elements instead of a text box. Please help. I am new to ASP.NET MVC. I need a solution / advice in Razor syntax.

+6
source share
4 answers
 @Html.DropDownListFor( model => model.Category, new SelectList(new [] {"cat1", "cat2", "cat3"}) ); 
+10
source

Here's how you could populate a DropDownList with Model, View, and Controller.

Performance first

 @using Website.Models @model PageWithSelectList @{ ViewBag.Title = "Index"; } @Html.DropDownList("DayOfWeek", Model.DaysOfWeek) 

Then the Controller method and Action

 using System.Web.Mvc; using Website.Models; namespace Website.Controllers { public class HomeController : Controller { public ActionResult Index() { var model = new PageWithSelectList(); model.DayOfWeek = 3; return View(model); } } } 

and HTML output

 <select id="DayOfWeek" name="DayOfWeek"> <option value="1">Sunday</option> <option value="2">Monday</option> <option selected="selected" value="3">Tuesday</option> <option value="4">Wednesday</option> <option value="5">Thursday</option> <option value="6">Friday</option> <option value="7">Saturday</option> </select> 

Hope this helps.

+3
source

Another way to populate your drop-down list is to use a browsing bag.

Controller:

 public Action Create() { FillViewBag(); Return View(); } private void FillViewBag() { List<SelectListItem> selectOptions = new List<SelectListItem>(); for(int i = 1; i <= 3; i++) { SelectListItem sli = new SelectListItem(); sli.Text = "Option " + i.ToString(); sli.Value = i.ToString(); selectOptions.Add(sli) } ViewBag.SelectOptions = selectOptions; } 

In your view:

  @Html.DropDownListFor(model => model.yourProp, ViewBag.SelectOptions as IEnumerable<SelectListItem>) 

Hope this helps you!

0
source

You can use fooowing code

Controler

 var list = new SelectList(new[] { new {ID="1",Name="Employee"}, new{ID="2",Name="Debtor"}, new{ID="3",Name="Supplier"}, new{ID="4",Name="Patient"}, }, "ID", "Name", 1); ViewData["list"] = list; return View(); 

View

 <div class="editor-field"> @Html.DropDownListFor(model => model.type,ViewData["list"] as SelectList, new { style = "width: 100px;"}) </div> 
0
source

Source: https://habr.com/ru/post/889733/


All Articles