2017-09-17 6 views
1

何らかの理由でDropDownListForが機能しません。その理由がわかりません。'HtmlHelper <Game>'に 'DropDownListFor'の定義が含まれていません

マイゲームモデル:

public class Game 
{ 
    public virtual int GameId { get; set; } 
    public virtual string Name { get; set; } 
    public virtual Studio Studio { get; set; } 
    public virtual Genre Genre { get; set; } 
    public virtual List<Level> Levels { get; set; } 
} 

マイコントローラ:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult MyEditEdit([Bind(Include = "GameId,Name,Genre")] Game game) 
{ 

    if(ModelState.IsValid) 
    { 
     db.Entry(game).State = EntityState.Modified; 
     db.SaveChanges(); 
     return RedirectToAction("MyEdit"); 
    } 
    return View(); 
} 

// GET 

public ActionResult MyEditEdit(int? id) 
{ 
    if (id == null) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
    } 
    Game game= db.Games.Single(g => g.GameId == id); 
    if(game == null) 
    { 
     return HttpNotFound(); 
    } 
    object genre; 
    if(game.Genre == null) 
    { 
     genre= 0; 
    } 
    else 
    { 
     genre= genre; 
    } 
    ViewBag.GenreList = new SelectList(db.Genres,"GenreId", "name", genre); 


    return View(game); 
} 

マイビュー:

@using GameStore.Controllers 
@using GameStore.Models 
@model GameStore.Models.Game 

@using (Html.BeginForm()) 
{ 
     <div class="form-group"> 
      @Html.LabelFor(model => model.Genre, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownListFor(m=>m.Genre, ViewBag.GenreList, "GenreId", "name") 
       @Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
} 

ビューもロードされない、と私はからのエラーを取得しますこの投稿のトピック。 DropDownListForラムダコードを書くと、インテリセンスはm => m.Genreでは機能しません。私は何が間違っているのか分からず、私は迷っています。私はそれをgoogledと何も見つけられませんでした。

答えて

1

私はあなたに似てDropDownListほとんどを移入する方法を示しています:

モデル

public class Department 
{ 
    public int DepartmentID { get; set; } 
    public string Code { get; set; } 
} 

コントローラー

public ActionResult Index() 
{ 
    MainDbContext db = new MainDbContext(); 
    var departments = (from c in db.Departments 
         select new Department 
         { 
          DepartmentID = c.Id, 
          Code = c.Code 
         }).ToList(); //Get department details 

    return View(departments); 
} 

ビュー - Inをビュー、foを使用llowing:

@model List<YourAppName.Models.Department> 
@{ 
    ViewBag.Title = "SampleApp"; 
} 

<select name="Department" id="Departments" class="form-control"> 
    <option value="0">--Please Select Department--</option> 
     @foreach (var item in Model) //Loop through the department to get department details 
     { 
     <option value="@item.DepartmentID">@item.Code</option> 
     } 
</select> 

ヒントViewBagを使用しないようにしてみて、上記のは、デモの目的のためです。代わりにViewModelを使用してみてください。

+0

ViewBagを使用して、ViewBagを使用しないように指示する例を示す理由は何ですか? – Wazner

+1

私はあなたが@ワーズナーのために求めていることを信じています。 –

関連する問題