假设我有一张简单的分组表,如图所示,
我想填充这个具有选项的下拉value
作为GroupID
和Name
作为text
像这里显示,
<select id="dropdown">
<option value="1">superadmin</option>
<option value="2">Support Desk</option>
<option value="3" selected="selected">SSL I</option>
<option value="4">SSL II Admin</option>
<option value="5">SSL II</option>
<option value="6">Client</option>
</select>
如何在不使用ViewModels和任何复杂性的情况下实现这一目标?其实我只想使用ViewBag来做到这一点?是否可以 ?
注意:此问题仅用于想法共享目的。请不要认为它太宽泛。
是的,我知道肯定有可能,
方法1:
在视图中,您可以像这样在此处简单地创建Dictionary<string, string>
和数据Dictionary
public ActionResult Index() {
var dictionary = new Dictionary<string, string>();
var allGroup = GetAllGroupNames(); //Query to get all data from table
foreach(var ag in allGroup)
{
dictionary.Add(ag.GroupId.ToString(), ag.Name);
}
ViewBag.selectGroupList = dictionary; // Add dictionary to ViewBag
return View();
}
然后,您的DropDownListFor
意志只会像这样,
@Html.DropDownListFor(model => model.GroupId, new SelectList((Dictionary<string,string>)ViewBag.selectGroupList, "Key", "Value",new { @id="dropdown"}))
方法2:
ViewBag.selectGroupList = new SelectList(GetAllGroupNames(), "GroupId", "Name");
并在视野中
@Html.DropDownListFor(model => model.GroupId, (SelectList)ViewBag.selectGroupList)
结果:
任何比这更好的方法将不胜感激
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句