【问题标题】:Populate DropDownListFor: HtmlHelper does not contain a definition for 'DropDownListFor'填充 DropDownListFor:HtmlHelper 不包含“DropDownListFor”的定义
【发布时间】:2018-09-10 20:05:32
【问题描述】:

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

我可以使用 ViewModel 或 ViewBag(我认为)来完成此操作。我正在尝试用 ViewBag 来做这件事。获取 DropDownListFor 错误:

CS1928 HtmlHelper<Survey> 不包含DropDownListFor 的定义并且最佳扩展方法重载SelectExtensions.DropDownListFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, IEnumerable<SelectListItem>, object) 有一些无效参数2_Views_Surveys_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>

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多