使用 Html.DropDownList 的第 5 个重载会导致异常。 (不包含 'DropDownList' 的定义和最佳扩展方法重载..)

Using 5th overload of Html.DropDownList causes exception. (does not contain a definition for 'DropDownList' and the best extension method overload..)

我有一个模型属性

public List<System.Web.Mvc.SelectListItem> ResponseTypes { get; set; }

在我看来,我认为这是导致错误的原因

error CS1928: 'System.Web.Mvc.HtmlHelper' 不包含 'DropDownList' 的定义和最佳扩展方法重载 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string

@Html.DropDownList("ResponseTypeId", "--Select Response Type--", question.ResponseTypes, new { @class = "form-control responseType", @id = "cbxType" })

我正在尝试使用 this 重载

public IHtmlString DropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes);

我似乎无法弄清楚这段代码有什么问题。我相信我已经正确地遵循了过载。

我也试过投射。不过我还是不行。

@Html.DropDownList("ResponseTypeId", "--Select Response Type--", (IEnumerable<SelectListItem>)question.ResponseTypes, new { @class = "form-control responseType", @id = "cbxType" })

您使用的是 System.Web.WebPages.Html 命名空间中的方法,而不是 System.Web.Mvc 命名空间中的方法。

你需要用到的是this overload签名处

public static MvcHtmlString DropDownList(
    this HtmlHelper htmlHelper,
    string name,
    IEnumerable<SelectListItem> selectList,
    string optionLabel,
    object htmlAttributes
)

因此您视图中的代码将是

@Html.DropDownList("ResponseTypeId", question.ResponseTypes, "--Select Response Type--", new { @class = "form-control responseType", id = "cbxType" })

但是我建议你使用强类型

@Html.DropDownListFor(m => m.ResponseTypeId, question.ResponseTypes, "--Select Response Type--", new { @class = "form-control responseType", id = "cbxType" })