除非使用强制类型转换,否则找不到MVC HtmlHelper扩展方法

时间:2018-07-05 20:21:55

标签: c# asp.net-mvc generics

我已经定义了一个名为BootstrapDropDownFor的扩展方法,其定义为

public static IHtmlString BootstrapDropDownFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, dynamic options, string defaultOption)

尝试在.cshtml文件中使用它

@Html.BootstrapDropDownFor(m => m.RequestType, ViewBag.RequestTypes, "-- Select --")

我收到以下错误:

'HtmlHelper<WebPermissionModel>' does not contain a definition for 'BootstrapDropDownFor' and the best extension method overload 'HtmlHelpers.BootstrapDropDownFor<TModel, TValue>(HtmlHelper<TModel>, Expression<Func<TModel, TValue>>, dynamic, string, string)' requires a receiver of type 'HtmlHelper<TModel>'

但是,通过将强制类型转换添加到options参数中,如下所示,我可以摆脱错误。

@Html.BootstrapDropDownFor(m => m.RequestType, (object) ViewBag.RequestTypes, "-- Select --")

添加演员表如何解决此问题?

1 个答案:

答案 0 :(得分:1)

扩展程序不支持

dynamic,请检查以下内容:

Extension methods cannot be dynamically dispatched

Extension method and dynamic object

What causes "extension methods cannot be dynamically dispatched" here?

在将动态类型传递给方法之前,必须显式转换动态类型

将动态参数更改为对象或确切类型:IEnumerable<SelectListItem>

public static IHtmlString BootstrapDropDownFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, IEnumerable<SelectListItem> options, string defaultOption = "-- select --")