vero
vero

Reputation: 243

Make asp.net razor template without view or controller

I have some code repetition across 5 pages, its a widget type of thing that's only needed sometimes. I want to make a "widget"-like cshtml template, without a model or view because it doesnt need any external data. I just need to "import" it into some places on my pages.

I am aware of tag helpers, but this is very HTML heavy and its annoying to have to type it in strings and stuff. I'd rather have nice syntax highlighting.

Upvotes: 0

Views: 855

Answers (1)

Jasen
Jasen

Reputation: 14250

You can use a Partial View without declaring a model or backing action.

_Privacy.cshtml

<div class="gdpr">
    <h2>Privacy</h2>
    <p>...</p>
</div>

Index.cshtml

...
<partial name="_Privacy" />

The prefixed underscore ("_") is naming convention for partial views.

Docs:

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-2.2

Partial Tag Helper The Partial Tag Helper requires ASP.NET Core 2.1 or later.

The Partial Tag Helper renders content asynchronously and uses an HTML-like syntax:

<partial name="_PartialName" />

When a file extension is present, the Tag Helper references a partial view that must be in the same folder as the markup file calling the partial view:

<partial name="_PartialName.cshtml" />

The following example references a partial view from the app root. Paths that start with a tilde-slash (~/) or a slash (/) refer to the app root:

Razor Pages

<partial name="~/Pages/Folder/_PartialName.cshtml" />
<partial name="/Pages/Folder/_PartialName.cshtml" />

MVC

<partial name="~/Views/Folder/_PartialName.cshtml" />
<partial name="/Views/Folder/_PartialName.cshtml" />

The following example references a partial view with a relative path:

<partial name="../Account/_PartialName.cshtml" />

Upvotes: 1

Related Questions