假设我有一个简单的组表,如图所示,
我想将此填充为下拉列表,其中选项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这样做?有可能吗?
注意:此问题仅适用于idea sharing purposes请不要将其视为过于宽泛。
答案 0 :(得分:1)
请按照以下步骤操作....
在Models文件夹下创建一个“AddressModel”类,并为标签字段和下拉列表值创建属性。
模型
public class AddressModel
{
public AddressModel()
{
AvailableCountries = new List<SelectListItem>();
AvailableStates = new List<SelectListItem>();
}
[Display(Name="Country")]
public int CountryId { get; set; }
public IList<SelectListItem> AvailableCountries { get; set; }
[Display(Name = "State")]
public int StateId { get; set; }
public IList<SelectListItem> AvailableStates { get; set; }
}
动作
public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableCountries.Add(new SelectListItem
{ Text = "-Please select-", Value = "Selects items" });
var countries = _repository.GetAllCountries();
foreach (var country in countries)
{
model.AvailableCountries.Add(new SelectListItem()
{
Text = country.Name,
Value = country.Id.ToString()
});
}
return View(model);
}
查看
@Html.LabelFor(model=>model.CountryId)
@Html.DropDownListFor(model=>model.CountryId, Model.AvailableCountries)
答案 1 :(得分:1)
public ActionResult Index()
{
var allGroup = GetAllGroupNames(); //Query to get all data from table
ViewBag.selectGroupList = allGroup ;
return View();
}
@Html.DropDownListFor(model => model.GroupId, new SelectList(ViewBag.selectGroupList, "Value", "Text",new { @id="dropdown"}))
答案 2 :(得分:0)
是的,我知道确定有可能,
方法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:
像 Stephen Muecke 建议的那样,
ViewBag.selectGroupList = new SelectList(GetAllGroupNames(), "GroupId", "Name");
并在视野中
@Html.DropDownListFor(model => model.GroupId, (SelectList)ViewBag.selectGroupList)
<强>结果:强>
任何更好的方法都会受到赞赏
答案 3 :(得分:0)
using (Context db = new Context()){
var tmp = db.group.ToList();
ViewBag.GroupId = new SelectList(tmp, "GroupId", "Name");
}
在视图
中@Html.DropDownListFor(model => model.GroupID, (SelectList)@ViewBag.GroupId)