MVC5 view drop down list

匿名 (未验证) 提交于 2019-12-03 02:54:01

问题:

In a C# MVC5 Internet application view, how can I display a dropdown list for a user to select a list item that is populated from a View Model list?

Here is the ViewModel code:

public class MapLocationItemViewModel {     [Editable(false)]     public int mapLocationForeignKeyId { get; set; }     public List<string> mapLocationItemTypes { get; set; }     public MapLocationItem mapLocationItem { get; set; } } 

Here is the code that I currently have in the View:

<div class="form-group">     @Html.LabelFor(model => model.mapLocationItem.mapLocationItemType, new { @class = "control-label col-md-2" })     <div class="col-md-10">         @Html.EditorFor(model => model.mapLocationItemTypes)     </div> </div> 

Each item in the mapLocationItemTypes is currently being displayed as a class="text-box single-line valid".

Is there a MVC View tag that will display a list that is populated from a list<string> or an array?

I have tried the following code:

@Html.DropDownListFor(model => model.mapLocationItemTypes) 

However, I am getting a compilation error, and am not sure as to the value(s) for the overloaded method.

How is the best way to display a list in a view, so that the user can select an list item from the list?

Thanks in advance

回答1:

Model :

 public List<SelectListItem> mapLocationItemTypes { get; set; }  public int mapLocationItemVal { get; set; } 

View:

@Html.DropDownListFor(m => m.mapLocationItemVal , new SelectList(Model.mapLocationItemTypes , "Value", "Text"), "  -----Select List-----  ") 

here in above example the 3rd parameter of DropDownListFor() i.e. " -----Select List----- " will be the initial selected item of your dropdown with value equal to ''.

At Controller during POST mapLocationItemVal will have selected dropdown value.

The above shown code is best and simplest way to bind Dropdownlist in MVC.



回答2:

Try this;

I assume you need to fill mapLocationItem.mapLocationItemType based on the selected value when you post the data.

@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes)) 

If you want to add CSS class you can do it as below.

@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes), new { @class = "your-class" }) 


回答3:

Create a method in your controller

Public ActionResult Index() {    SampleDBContext db = new SampleDBContext();    ViewBag.table_name = new SelectList(db.table_name, "DataValueField", "DataTextField");     return View(); }  

View of the Controller

@Html.DropDownList("table_name", "select a item") 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!