2
我正在編寫需要與dropdownlist綁定的MVC列表頁面。
由於我是ASP.net MVC的初中,我不知道如何使dropdownlist正確運行並動態選擇。使用模型類綁定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);
}
...
}
然後一個刮刀文件,
<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)我怎樣才能動態選擇項目?
每一個建議將非常感激。
非常感謝你的回答非常有幫助@Eranga。 – 2012-01-10 09:43:14