MVC5 view drop down list

2020-06-04 12:58发布

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

3条回答
劳资没心,怎么记你
2楼-- · 2020-06-04 13:41

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.

查看更多
何必那么认真
3楼-- · 2020-06-04 13:44

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" })
查看更多
够拽才男人
4楼-- · 2020-06-04 13:59

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")
查看更多
登录 后发表回答