Partial HTML

December 25, 2020

In Asp.Net Core server-side rendered HTML, you have the ability to use something called Partial Views. Essentially, these give you the ability to separate your View into, what some JS frameworks may call, components.

The way it works is incredibly simple. In your main page, you define some HTML, and reference the partial view - like so:

[code lang=“html”]

Merry Christmas - here's my partial view:

@await Html.PartialAsync("\_MyPartial", Model.MyData)



In your partial view, which is simply another cshtml file, you define the HTML fragment, along with the model; for example:

[code lang="html"]
@model IEnumerable<MyDataType>

@foreach (var item in Model)
{
    <p>item.Data</p>
    <br />
}

References

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



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024