MVC5视图下拉列表
在C#MVC5 Internet应用程序视图中,如何显示下拉列表以供用户选择从“ View Model
列表中填充的列表项?
这是ViewModel
代码:
public class MapLocationItemViewModel { [Editable(false)] public int mapLocationForeignKeyId { get; set; } public List mapLocationItemTypes { get; set; } public MapLocationItem mapLocationItem { get; set; } }
这是我目前在View
的代码:
@Html.LabelFor(model => model.mapLocationItem.mapLocationItemType, new { @class = "control-label col-md-2" }) @Html.EditorFor(model => model.mapLocationItemTypes)
mapLocationItemTypes
中的每个项目当前都显示为class="text-box single-line valid"
。
是否有MVC View标记,它将显示从list
或array
填充的list
?
我试过以下代码:
@Html.DropDownListFor(model => model.mapLocationItemTypes)
但是,我收到编译错误,并且不确定重载方法的值。
如何在视图中显示列表的最佳方式,以便用户可以从列表中选择列表项?
提前致谢
型号:
public List mapLocationItemTypes { get; set; } public int mapLocationItemVal { get; set; }
视图:
@Html.DropDownListFor(m => m.mapLocationItemVal , new SelectList(Model.mapLocationItemTypes , "Value", "Text"), " -----Select List----- ")
在上面的示例中, DropDownListFor()
的第三个参数即" -----Select List----- "
将是您的下拉列表的初始选定项目,其值等于''
。
在POST期间,在控制器中, mapLocationItemVal
将具有选定的下拉值。
上面显示的代码是在MVC中绑定Dropdownlist的最佳和最简单的方法。
试试这个;
我假设您需要在发布数据时根据所选值填充mapLocationItem.mapLocationItemType
。
@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes))
如果要添加CSS类,可以按照以下方式执行。
@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes), new { @class = "your-class" })
在控制器中创建方法
Public ActionResult Index() { SampleDBContext db = new SampleDBContext(); ViewBag.table_name = new SelectList(db.table_name, "DataValueField", "DataTextField"); return View(); }
控制器的视图
@Html.DropDownList("table_name", "select a item")