Populate DropDownListFor: HtmlHelper does not contain a definition for 'DropDownListFor'

≡放荡痞女 提交于 2021-02-11 12:36:11

问题


I have an ever-changing list of Industries that I'd like a user to select from when creating a new Survey.

I could accomplish this with either a ViewModel or ViewBag (I think). I'm attempting to do it with ViewBag. Getting the DropDownListFor error:

CS1928 HtmlHelper<Survey> does not contain a definition for DropDownListFor and the best extension method overload SelectExtensions.DropDownListFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, IEnumerable<SelectListItem>, object) has some invalid arguments 2_Views_Surveys_Create.cshtml

Survey model, with foreign key to Industry:

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

}

Controller to load Industries SelectList into ViewBag:

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

Create 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>

回答1:


Properties of the ViewBag have no type that the compiler can use to decide which overload of the method to call. Help the compiler by using an explicit cast.

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


来源:https://stackoverflow.com/questions/52264750/populate-dropdownlistfor-htmlhelper-does-not-contain-a-definition-for-dropdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!