首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >填充DropDownListFor: HtmlHelper不包含“DropDownListFor”的定义

填充DropDownListFor: HtmlHelper不包含“DropDownListFor”的定义
EN

Stack Overflow用户
提问于 2018-09-10 20:05:32
回答 1查看 1.2K关注 0票数 0

我有一个不断变化的行业名单,我希望用户选择时,创建一个新的调查。

我可以通过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。

调查模式,带有外键的工业:

代码语言:javascript
复制
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; }

}

将工业SelectList加载到ViewBag的控制器:

代码语言:javascript
复制
// GET: Surveys/Create
public ActionResult Create()
{
    ViewBag.Industries = new SelectList(db.industry, "Id", "Name");
    return View();
}

创建视图:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-10 20:27:46

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

代码语言:javascript
复制
@Html.DropDownListFor(model => model.industryId, (IEnumerable<SelectListItem>)ViewBag.Industries, "-Select Industry-")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52264750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档