1

I've defined an extension method called BootstrapDropDownFor which has a definition of

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

When trying to use it in a .cshtml file

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

I get the following error:

'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>'

However, by adding a cast to the options parameter, as below, I can get rid of the error.

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

How come adding a cast fixes this issue?

hdt80
  • 639
  • 1
  • 8
  • 14
  • 1
    `dynamic` types in extension methods are not supported (`ViewBag` is `dynamic`) –  Jul 05 '18 at 22:03

1 Answers1

1

dynamic is not supported in extension, check these:

Extension methods cannot be dynamically dispatched

Extension method and dynamic object

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

You must cast dynamic type explicitly before you pass it to method

change dynamic parameter to object or exact type: IEnumerable<SelectListItem>

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

Dongdong
  • 2,208
  • 19
  • 28
  • Same error. It looks like no matter what I set `options`'s type to be, it will always throw that error. I'm not a fan of the second one either as the way the function works allows it to be many different types. – hdt80 Jul 05 '18 at 20:47
  • ANSWER UPDATED. no matter what object will be in dynamic, it will be converted to IEnumerable inside your extension. why not explicitly declare parameter as IEnumerable since it's the data that dropdown excepts. and "dynamic" could confuse teammate: what should be in dynamic object? – Dongdong Jul 06 '18 at 15:58