我正在编写需要捆绑下拉列表的MVC列表页面 因为我非常初级到ASP.net MVC,我不知道如何让dropdownlist正确运行并动态选择。
我有两个模型类
public class CycleType
{
public int CycleTypeID { get; set; }
public string Type { get; set; }
public List<CycleModel> CycleModels { get; set; }
}
-----------------------------------------------------------
public class CycleModel
{
public int CycleModelID { get; set; }
public int CycleTypeID { get; set; }
public string Model { get; set; }
public virtual CycleType CycleType { get; set; }
}
然后是一个Controller类,
public class CycleModelController : Controller
{
UnitOfWork<CycleModel> unitOfWork = new UnitOfWork<CycleModel>();
UnitOfWork<CycleType> unitOfWork_cycleType = new UnitOfWork<CycleType>();
...
[HttpGet]
public ActionResult Edit(int CycleModelID)
{
CycleModel cycleModel = unitOfWork.GenericTEntityRepository.GetByID(CycleModelID);
ViewBag.CycleType = new SelectList(unitOfWork_cycleType.GenericTEntityRepository.Get(orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)));
return View(cycleModel);
}
...
}
然后是一个Razor文件,
<div class="editor-field">
@*Html.DropDownList("CycleType")*@
@*Html.EditorFor(model => model.CycleTypeID)*@
@Html.DropDownListFor(model => model.CycleTypeID,
new SelectList(ViewBag.CycleType, "Type", "CycleTypeID"))
@Html.ValidationMessageFor(model => model.CycleTypeID)
</div>
当我运行程序时,收到错误消息
DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Type'.
1)我怎样才能使这段代码正确?
2)如何动态选择项目?
每个建议都会非常感激。
答案 0 :(得分:2)
ViewBag.CycleType
已经是SelectList
。因此,您可以直接使用它。
@Html.DropDownListFor(model => model.CycleTypeID, (SelectList)ViewBag.CycleType)
您可以按如下方式更改控制器代码。
ViewBag.CycleType = new SelectList(
unitOfWork_cycleType.GenericTEntityRepository.Get(
orderBy: CycleTypes => CycleTypes.OrderBy(CycleType => CycleType.Type)),
"Type", "CycleTypeID");