2017-09-17 76 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 lambda代碼時,intelisense不適用於m => m.Genre。我不知道我做錯了什麼,我迷路了。我GOOGLE了它,並沒有發現任何東西。

回答

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

查看 - 在該視圖,使用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

我相信,以上你所要求的@Wazner。 –

相關問題