我想将强类型对象的列表传递给位于我视图中的下拉列表。
通常为了达到这个目的,我使用了以下示例中的ViewBags:
public ActionResult ChooseLevel()
{
List<Levels> LevelList = GetAllLevels();
ViewBag.LevelList = LevelList
var model = new Levels();
return View(model);
}
我只想在一个视图上写这个,我会把所有级别列在那里:
<div class="form-group">
@Html.LabelFor(model => model.LevelId, new { @class = "control-label col-md-3 col-sm-3" })
<div class="col-md-9 col-sm-9">
@Html.DropDownListFor(model => model.LevelId, new SelectList(ViewBag.LevelList, "LevelId", "LevelName"), "", new { @class = "form-control" })
</div>
</div>
但是现在我想知道我可以简单地传递我的Levels列表,并从下拉列表中选择它们,而不是先将它们存储到viewbag中吗? 例如:
public ActionResult ChooseLevel()
{
List<Levels> LevelList = GetAllLevels();
return View(LevelList);
}
在视图中,我会通过在视图上写IEnumerable
来接受多个项目:
@model IEnumerable<Levels>
之后,我可以选择一个项目并将其发回服务器?
我该如何解决这个问题?
答案 0 :(得分:2)
您需要将此列表添加到现有的模型或视图模型中:
class ModelName
{
public virtual IEnumerable<SelectListItem> lstTypes { get; set; }
public virtual int intTypeId { get; set; }
//Other existing properties here
}
在您的控制器上,您现在可以在返回视图之前将此列表添加到模型中:
ModelName objModel = new ModelName();
List<Levels> LevelList = GetAllLevels();
objModel.lstTypes = LevelList.Select(y => new SelectListItem()
{
Value = y.LevelId.ToString(),
Text = y.LevelName.ToString()
});
return View(objModel);
然后,您现在可以在视图中显示它:
@model ModelName
//First parameter will be the Id that will be selected by your user when they post it
//Second parameter will be the enumerable list of dropdown
//Third parameter is the default option which is optional, and the last is the HTML attributes
@Html.DropDownListFor(c => c.intTypeId, Model.lstTypes , "Please select an item", new { @class = "form-control" })
答案 1 :(得分:1)
您可以创建包含多个模型的新视图模型(旧模型和LevelList模型)。像这样:
public class newViewModel
{
public IEnumerable<level> levels{ get; set;}
public OldModel oldModel {get; set;}
}
答案 2 :(得分:0)
模型类
public class TestViewModel
{
public List<SelectListItem> EnterpriseList { get; set; }
}
控制器:
var model = new TestViewModel() {
EnterpriseList = EnterpriseData.Select(p=>new SelectListItem() { Value = p.Value,Text = p.Name}).ToList()
};
return View(model);
查看:
@Html.DropDownListFor(p => p.Enterprise, Model.EnterpriseList, "Please select a", new { @class = "form-control", @style = "height: auto" })