Asp.net mvc 填充DropDownListFor:HtmlHelper不包含“DropDownListFor”的定义

Asp.net mvc 填充DropDownListFor:HtmlHelper不包含“DropDownListFor”的定义,asp.net-mvc,Asp.net Mvc,我有一个不断变化的行业列表,我希望用户在创建新调查时从中进行选择 我想我可以用ViewModel或ViewBag来实现这一点。我正试图用ViewBag来做这件事。获取DropDownListFor错误: CS1928 HtmlHelper不包含DropDownListFor的定义,最佳扩展方法重载SelectExtensions。DropDownListForHtmlHelper,Expression,IEnumerable,对象具有一些无效参数2\u Views\u Surveys\u Cre

我有一个不断变化的行业列表,我希望用户在创建新调查时从中进行选择

我想我可以用ViewModel或ViewBag来实现这一点。我正试图用ViewBag来做这件事。获取DropDownListFor错误:

CS1928 HtmlHelper不包含DropDownListFor的定义,最佳扩展方法重载SelectExtensions。DropDownListForHtmlHelper,Expression,IEnumerable,对象具有一些无效参数2\u Views\u Surveys\u Create.cshtml

调查模型,外键指向行业:

public class Survey
    {
        [Key]
        public int id { get; set; }

    [Display(Name = "Survey Name")]
    public string name { get; set; }

    [Display(Name = "Industry")]
    public int industryId { get; set; }

    [ForeignKey("industryId")]
    public virtual Industry industry { get; set; }

}
要将Industries SelectList加载到ViewBag中的控制器:

// GET: Surveys/Create
public ActionResult Create()
{
    ViewBag.Industries = new SelectList(db.industry, "Id", "Name");
    return View();
}
创建视图:

<div class="form-group">
    @Html.LabelFor(model => model.industryId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.industryId, ViewBag.Industries, "-Select Industry-")
        @Html.ValidationMessageFor(model => model.industryId, "", new { @class = "text-danger" })
    </div>
</div>

ViewBag的属性没有编译器可以用来决定调用哪个方法重载的类型。通过使用显式强制转换帮助编译器

@Html.DropDownListFor(model => model.industryId, (IEnumerable<SelectListItem>)ViewBag.Industries, "-Select Industry-")