Use a variable to reference a partial view's location

Viewed 570

I am new to asp.net core and am trying to render a partial view in an ASP.Net Core application. The address of the partial view is determined at run time. I have constructed a view model which is parsed into the view from the controller and contains the desired file address.

The following code throws the following compiler error:

@Html.Partial(Model.File);

Error CS1973 'IHtmlHelper' has no applicable method named 'Partial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Any help would be greatly appreciated.

2 Answers

Just to add to Lachlan Fergusson's excellent answer (thank you!) just to say that you also get this message if the name of your view contains a variable, without it's type.

So, the following line threw the error for me:

@Html.Partial("UserDetailsPartial." + language, Model)

...but it went away when I added this...

@Html.Partial("UserDetailsPartial." + (string)language, Model)

Behind the scenes, I had different partials based on language,

UserDetailsPartial.es.html
UserDetailsPartial.de.html
UserDetailsPartial.fr.html

The strange thing is that previously (with an earlier version of .Net Core?) the original line worked fine.

So, add this to Microsoft's "list of error messages which don't really explain what the problem is.."

Related