2016-06-26 5 views
2

私はEFとMVC、新しいものと一緒に働いています。 は、私は、次のクラスがあります。c#MVC - クラスプロパティからDropDownListを取り込みます

public class Client 
{ 
    [Key] 
    public int ClientId { get; set; } 
    public Category Category { get; set; } 

} 

を、私は「作成」のActionResult、いずれかを選択するために、すべてのカテゴリで選択DropDownListコントロールに関連したビューに表示します。

また、私はViewModelに持っている:私は、コントローラで使用

public class CategoryViewModel 
{ 
    public int SelectedCategoryId { get; set; } 
    public IEnumerable<SelectListItem> Categories { get; set; } 
} 

private IEnumerable<SelectListItem> GetCategories() 
    { 
     var db = new MyDBContext(); 
     var categories = db.Categories 
        .Select(x => 
          new Category 
          { 
           CategoryId = x.CategoryId, 
           Name = x.Name 
          }); 

     return new SelectList(categories, "Value", "Text"); 
    } 

...とでは)(作成:

public ActionResult Create() 
    { 
     var model = new CategoryViewModel(); 
     model.Categories = GetCategories(); 
     return View(model); 
    } 

私がいけませんのビューでのプルダウンの設定方法を知っている:

<div class="form-group"> 
     @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownListFor(WHAT GOES HERE????) 

     </div> 
    </div> 

私を救ってくれてありがとう! (RE5の引用)

+0

'@ Html.DropDownListFor(M => m.SelectedCategoryId、モデルを使用します.Categories) 'しかし、あなたの' GetCategories() 'メソッドは間違っており、例外がスローされます。 'return db.Categories.Select(x => new SelectListItem {Value = x.CategoryId.ToString()、Text = x.Name});' –

答えて

2

overloads異なるありますが、これはオプションです:

@Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories) 
0

てみてください。このコードに

@Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories) 
関連する問題