[英]How can I pass list of strongly type objects from controller to a dropdown on a view?
我想将强类型对象的列表传递给位于我视图中的下拉列表。
通常要实现此目的,我使用了以下示例中的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>
但是现在我想知道我是否可以仅将我的“级别”列表传递到那里,然后从下拉列表中选择它们,而不必先将它们存储到视图包中? 例如 :
public ActionResult ChooseLevel()
{
List<Levels> LevelList = GetAllLevels();
return View(LevelList);
}
在视图上,我可以通过在视图上编写IEnumerable
来接受多个项目:
@model IEnumerable<Levels>
之后,我可以以某种方式只选择一项并将其发布回服务器?
我该如何解决这个问题?
您需要将此列表添加到现有模型或视图模型中:
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" })
您可以创建包含多个模型(旧模型和LevelList模型)的新viewmodel。 像这样:
public class newViewModel
{
public IEnumerable<level> levels{ get; set;}
public OldModel oldModel {get; set;}
}
模型类
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" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.