Aleksey Shubin
Aleksey Shubin

Reputation: 1998

Pass inner HTML to Partial View in ASP.NET Core MVC 3

I'm sure this question has already been asked but don't know how to phrase it correctly. I want to do something like that:

MyView.cshtml:

<partial name="_MyPartial">
    <span>some content</div>
</partial>

_MyPartial.cshtml:

<div class="partial">
    @RenderInnerHtml()
</div>

and the result is:

<div class="partial">
    <span>some content</div>
</div>

Is it possible? If not with Partial Views, then with View Components perhaps?

Upvotes: 4

Views: 1039

Answers (1)

Mark Jerzykowski
Mark Jerzykowski

Reputation: 982

For aspnet core razor take a look at "Templated Razor delegates" documentation

With those you can create razor templates using the syntax:

Func<T, object> template = @<div>@item.Foo</div>;

(where T is your type).

You can then pass that function around (in to partial views for example) and invoke as such:

@template(new T { Foo = "Bar" })

Notice that the parameter passed in is accessed via @item. (My VS adds a red squiggle for this but it can be ignored!)

If you don't want a strongly typed template, just change T to dynamic.

For your particular use case:

@{
    var template = @<span>some content</span>;
}

<partial name="_MyPartial" model="template" />

Then, inside _MyPartial:

@Model(null)

Obviously, you can introduce multiple templates and stronly typed models for the partial.

Upvotes: 1

Related Questions