Using the the partial tag helper with models in .NET Core 2.1 and later

.Net Core 2.1 introduces the partial tag helper.  This post shows two useful ways to use this tag helper.

Example to display sample websites

This example uses a model to display a list of sample websites that have been produced by your company. We require the sample company name, some short text about the company, a screenshot of the website, and some alt text.

The Model

public class Sample
     {
         public string company { get; set; }
         public string text { get; set; }
         public string img { get; set; }
         public string alt { get; set; }
     }

To display the sample company information we will call a partial view for each company.. The partial view is shown below and is called samplesCase.

The Partial View

     
<div>
    <div>
        <section>
            <h4>@Model.company</h4>
            <div>
                <p>
                    @Html.Raw(@Model.text)
                </p>
            </div>
            <img src="@Model.img" alt="@Model.alt">
        </section>
    </div>
</div>
                                           

Use partial tag helpers to display data

Next, in my view, I create two instances of the model and add the partial tag helpers. This will display information about two websites.

@{
Sample s1 = new Sample();
    s1.company = "Learn Page by Page";
    s1.text = @"Learn Page by Page uses popular fiction as a launch pad for learning English as a foreign language.";
    s1.img = @Url.Content("~/Images/screenshots/learnPageByPage.png");
    s1.alt = @"Screenshot of Learn Page by Page, learnpagebypage.com";

   Sample s2 = new Sample();
    s2.company = "Today Web Host";
    s2.text = @"Today Web Host provides hosting services for Windows and  Linux, including Wordpress.";
    s2.img = @Url.Content("~/Images/screenshots/todaywebhost.png");
    s2.alt = @"Screenshot of Today Web Host website, todaywebhost.com";
}
<partial name="samplesCase" , model=@s1 />
<partial name="samplesCase" , model=@s2 />

Note that the partial tag helper calls the name of the partial view and the model instance to use. You can also create a new instance of the model within the tag itself.

<partial name="samplesCase", model='new Sample{company="sample company", text="sample text" , img=@Url.Content("~/Images/screenshots/todaywebhost.png") , alt="sample alt" }' />

Leave a Reply

Your email address will not be published. Required fields are marked *