0
votes

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

1 Answers

1
votes

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-")