'HtmlHelper <game>'不包含'DropDownListFor'的定义

时间:2017-09-17 15:53:21

标签: c# asp.net-mvc razor

出于某种原因,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>
}

View甚至没有加载,我从这篇文章的主题中得到了错误。当我编写DropDownListFor lambda代码时,intelisense对m => m.Genre不起作用。我不知道我做错了什么,我迷路了。我用Google搜索并没有找到任何东西。

1 个答案:

答案 0 :(得分: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);
 }

查看 - 在视图中,使用以下内容:

@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