2012-01-10 8 views
2

私はドロップダウンリストとバンドルする必要があるMVCリストページを書いています。
私はASP.net MVCの後輩であるため、正しく実行され、動的に選択されるようにドロップダウンリストを作成する方法はわかりません。モデルクラスを使用したAsp.net MVCドロップダウンリストのバインド

私は私が私のプログラムを実行すると、その後の一つカミソリファイル、

<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> 

が、私はエラーメッセージが表示されます2つのモデルクラス

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); 
} 

... 
} 

DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Type'. 

1)どうすればこのコードを修正できますか?
2)どのように選択項目を動的にすることができますか?

すべての提案は本当に感謝しています。

答えて

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"); 
+0

非常に有益な回答@Erangaをありがとうございました。 –

関連する問題