MVC5视图下拉列表

MVC5视图下拉列表

本文介绍了MVC5视图下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#MVC5 Internet应用程序视图中,如何显示下拉列表供用户选择从View Model列表填充的列表项?

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?

这是ViewModel代码:

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

这是我目前在View中拥有的代码:

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>

mapLocationItemTypes中的每个项目当前都显示为class="text-box single-line valid".

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

是否有一个MVC View标记将显示从list<string>array填充的列表?

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

我尝试了以下代码:

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

预先感谢

推荐答案

模型:

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

查看:

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

在上面的示例中,DropDownListFor()的第三个参数,即" -----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 ''.

在POST期间的Controller上,mapLocationItemVal将选择下拉列表值.

At Controller during POST mapLocationItemVal will have selected dropdown value.

上面显示的代码是在MVC中绑定Dropdownlist的最好和最简单的方法.

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

这篇关于MVC5视图下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:54