-
21-12-2019 - |
题
在 C# MVC5 Internet 应用程序视图中,如何显示下拉列表以供用户选择从 View Model
列表?
这里是 ViewModel
代码:
public class MapLocationItemViewModel
{
[Editable(false)]
public int mapLocationForeignKeyId { get; set; }
public List<string> mapLocationItemTypes { get; set; }
public MapLocationItem mapLocationItem { get; set; }
}
这是我目前在的代码 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"
.
是否有一个 MVC 视图标签将显示一个由 list<string>
或一个 array
?
我尝试过以下代码:
@Html.DropDownListFor(model => model.mapLocationItemTypes)
但是,我收到编译错误,并且不确定重载方法的值。
在视图中显示列表以便用户可以从列表中选择列表项的最佳方式是什么?
提前致谢
解决方案
模型 :
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()
IE。 " -----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")
不隶属于 StackOverflow