4

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?

1
  • 2
    Partial views and view components do not support child content. You might want to look at Razor Components instead: mikesdotnetting.com/article/338/…. They support child content. Commented Nov 7, 2019 at 9:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.