Skip to content
  • iImagine
  • Register
  • Log In

Web Development School

Learning made easy.

  • Books
    • Beginning Web Development with ASP.Net Core & Client-Side Technologies
      • TOC
      • Part 1
        • Chapter 1: Static HTML – Designing the landing page
      • Part 2
        • Chapter 2: ASP.Net Core – Let’s talk Dynamic
        • Chapter 3: Introduction to ASP.Net Core MVC
          [ASP.Net Core v9]
      • Part 4
        • Chapter 7: Using Server Side & Client Side technologies together
          [ASP.Net Core v7 & Angular 15]
  • Environment Setup
    • Installing Angular
    • Installing Visual Studio 2022
    • Installing SQL Server 2022 Express
    • Installing Postman
    • Installing Git for Windows
  • Blog
  • iImagine WebSolutions
  • Events
  • Learning Videos
  • Toggle search form

Partial View: Break out the vehicle results

In the last module we completed the category filter feature for the vehicle results on the main page of the application. In this module we are going to break out the code (HTML, Razor, and C#) for a single vehicle result, or one table row representing a single vehicle, into a template using a partial view.

A partial view in ASP.NET Core MVC is a reusable component with a fragment of code containing HTML, Razor, and C# that can represent a portion of a web page. It’s similar to a regular view, but is intended to be encapsulated in other views, rather than being rendered on its own.

Some key benefits of partial views are they help avoid code duplication and are reusable. But, I like using them to break out longer pieces of html and razor to make the main page the partial view will sit in more readable. That way you’re not forced to look at all of the logic in one file. You can get an idea of the flow of the Index file just by seeing a call to to a partial view, in this case to layout vehicle results in html table rows.

Table Of Contents
  1. Create the Partial View
  2. Call a Partial View from a Parent View
  3. What's Next

Create the Partial View

In the Views/Home folder, create a Razor file named _VehicleTableRowResult.cshtml

FredsCars\Views\Home_VehicleTableRowResult.cshtml

@model Vehicle

<tr>
    <td>
        <img src="@Model.ImagePath"
             class="result-image" />
    </td>
    <td>
        @Html.DisplayFor(modelItem => Model.Status)
    </td>
    <td>
        @Html.DisplayFor(modelItem => Model.Year)
    </td>
    <td>
        @Html.DisplayFor(modelItem => Model.Make)
    </td>
    <td>
        @Html.DisplayFor(modelItem => Model.Model)
    </td>
    <td class="d-none d-lg-table-cell">
        @Html.DisplayFor(modelItem => Model.Color)
    </td>
    <td class="d-none d-md-table-cell">
        @Html.DisplayFor(modelItem => Model.Price)
    </td>
    <td class="d-none d-md-table-cell">
        @Html.DisplayFor(modelItem => Model.VehicleType.Name)
    </td>
</tr>

In the razor code above, we have basically cut the code from the parent Home/Index view that creates a vehicle table row result for each vehicle in the foreach loop and copied it to the new partial view.

We named the view starting with an underscore ‘_’ character. Starting a view name with an underscore character signifies that the razor file should not be loaded on it’s own. You don’t have to use this convention but I find it helpful to identify partial views more easily.

We placed the partial view in the Views/Home folder. In this location, only action methods in the Home controller will be able to find this partial view. I did this because embedding a result in a table row is not truly reusable because we are forced to place the result in a tbody or table html element.

If we truly wanted this component to be reusable we would place it in the Views/Shared folder. In this location any action method from any controller would be able to find this view. I would have been more likely to place the view in the Shared folder if we were using div elements to encapsulate a result and the Bootstrap grid system like we did in Chapter One. But in this chapter I wanted to show a common layout theme in web applications; a table and table rows to show results. This layout also makes it easier to show the sorting feature. In Chapter four, ASP.Net Core Razor Pages – PageModels and Views, we will return to our original layout with three Vehicle results per row in an HTML div element using the Bootstrap Grid system.


At the top of the Razor file the model is defined as type Vehicle.

@model Vehicle

We access each property of a Vehicle to lay out in results using the Model property of a Razor view file instead of ‘v’ in the
foreach (var v in Model.Vehicles) loop we were previously using in the parent view.
The following is an example using the Status property of a Vehicle.

<td>
    @Html.DisplayFor(modelItem => Model.Status)
</td>

Call a Partial View from a Parent View

Now we need to make a call to the _VehicleTableRowResult partial view from the Home/Index parent view. Make the following modification to the Index.chtml file in the Views/Home folder.

FredsCars\Views\Home\Index.cshtml

@model VehiclesListViewModel

@{
    ViewData["Title"] = "Welcome";
}

<div class="container-fluid my-4 text-center">
    <h1>Welcome to Fred's Cars!</h1>
    Where you'll always find the right car, truck, or jeep.<br />
    Thank you for visiting our site!

    <div class="container-fluid mx-0 row"
        style="margin-top: 20px;">
        <!-- Categories -->
        ... existing code ...
        <!-- Results -->
        <div class="col">
            <h3 class="bg-dark text-success">ALL Results</h3>
            <table class="results table table-striped">
                <thead>
                    ... existing code ...
                </thead>
                <tbody>
                    @foreach (var v in Model.Vehicles)
                    {
                        <partial name="_VehicleTableRowResult"
                            model="v" />
                    }
                </tbody>
            </table>
    
             <div id="page-links"
                  page-model="@Model.PagingInfo"
                  page-action="Index"
                  paging-classes-enabled="true"
                  paging-btn-class="btn"
                  paging-btn-class-normal="btn-outline-dark"
                  paging-btn-class-selected="btn-primary"
                  sort-column="@Model.SortingInfo.CurrentSortColumn"
                  sort-order="@Model.SortingInfo.CurrentSortOrder"
                  class="btn-group mt-3">
             </div>
        </div>
    </div>  
</div>

In the parent Home/Index razor view above, instead of laying out seven html td elements for each Vehicle iteration in the forloop, we simply make a call to a template encapsulated in a partial view.

 @foreach (var v in Model.Vehicles)
 {
     <partial name="_VehicleTableRowResult"
         model="v" />
 }

In the code snippet above, we make the call to the _VehicleTableRowResult partial view using the partial tag helper. The tag helper’s name attribute is assigned the name of the partial view to call without the .cshtml extension. And we use the model attribute to pass the variable v representing the Vehicle object in each iteration of the forloop.

If you restart the application and run it there should be no changes from before and the behavior as far as filtering, paging and sorting should remain the same.

What’s Next

In this module we broke out the Vehicle result table rows into a template using a partial view.
In the next module we will learn about View Components and make the category buttons section dynamic.

< Prev
Next >

Leave a ReplyCancel reply

Chapter 1: Static HTML – Designing the landing page.

  • Static HTML – Designing the landing page.
  • Let’s get started!
  • Mock your site with HTML
  • Make CSS easy with Bootstrap
  • Mock your content
  • Introducing JavaScript
  • JavaScript Code Improvements
  • Results Data
  • Images and the HTML Image Element.
  • Revisiting Reusability for CSS and JavaScript
  • Reuse for HTML: PART 1
  • Reuse for HTML: PART 2
  • Details Page – Using a Bootstrap Component
  • Creating Links
  • Chapter One Conclusion

Chapter 2: ASP.Net Core – Let’s talk Dynamic

  • Introduction to ASP.Net Core
  • What is .Net?
  • What is ASP.Net
  • Introduction to Entity Framework Core

Chapter 3: ASP.Net MVC Core – Models, Views, and Controllers [ASP.Net Core v9]

  • Introduction to ASP.Net Core MVC
  • Create the project: ASP.Net Core MVC
  • Explore the ASP.Net Core Empty Web Project Template
  • Configure the Application for MVC
  • Create a Controller: Home Controller
  • Create a View: Index View for the Home Controller
  • Install Bootstrap using Libman
  • Create the Layout template
  • Create the Model
  • Install EF Core & Create the Database
  • Seed the Database: Loading test data
  • DI (Dependency Injection): Display a List of Vehicles
  • Repository Pattern: The Vehicles Repo
  • Unit Test 1: Home Controller Can Use Vehicle Repository
  • Unit Test 2: Vehicle Repository Can Return List
  • Add the ImagePath Migration and Thumbnail images to results
  • Pagination: Create a Custom Tag Helper
  • Sorting
  • Category Filter
  • Partial View: Break out the vehicle results
  • View Component: Create dynamic category buttons
  • Create the Details page
  • Create the Create Page

Chapter 7: Using Server Side & Client Side technologies together. [ASP.Net Core v7 & Angular v15]

  • Intro to Full Stack Development
  • Fred’s Cars – Full Stack Development
  • Prepare the environment
  • Create the Visual Studio Solution
  • Add the ASP.Net Core Web API project
  • Add the Angular Project
  • Wire it up!
  • WeatherForecast: Understanding the basics
  • Vehicles API Controller: Mock Data
  • Vehicles Angular Component: Consuming Data
  • Routing and Navigation
  • Using a Component Library: Angular Material
  • Our first Angular Material Component: MatToolbar
  • Configuring for Saas: CSS with superpowers
  • Create the Header & Footer components
  • Displaying Results with MatTable
  • Loading: Using a Progress Spinner
  • MatTable: Client-Side Paging and Sorting
  • MatSidenav: Create a Search Sidebar
  • MatCheckbox: Category Search UI
  • Adding an image to the welcome page
  • Create the database with Entity Framework Core migrations
  • MatPaginator & PageEvent: Custom Server-Side Paging
  • Unit Testing: Custom Server-Side Paging
  • Repository Pattern: VehicleRepository
  • Unit Test: Paging in the Vehicles controller
  • Server-Side Sorting
  • Unit Tests: Sorting
  • Filter (Quick Search)
  • Unit Tests: Filter feature
  • Advanced Search: Categories
  • Unit Tests: Search by category
  • Progress Spinner: Final Fix

TOC

  • What were WebForms?
  • Enter MVC
    • Understanding MVC
    • Advantages of MVC
  • ASP.Net Core MVC – A total rewrite
  • ASP.Net Core 2 MVC – Here come Razor Pages
    • Understanding Razor Pages
  • ASP.Net Core 3 – Dropping the MVC reference
    • Understanding Blazor
  • Dropping the MVC reference
  • Hello .Net 5!
  • What’s Next? – Here comes .Net 6.

Recent Posts

  • Angular Commands Cheat Sheet
  • Installing Git for Windows
  • Installing Postman
  • Installing SQL Server 2022 Express
  • Installing Visual Studio 2022

Recent Comments

No comments to show.

Archives

  • November 2023
  • October 2023
  • June 2023
  • October 2021

Categories

  • Angular
  • ASP.Net
  • Environment Setup
  • See All
  • SQL Server
  • Visual Studio
  • Web API & Rest Services

WordPress Theme Editor

Copyright © 2025 Web Development School.

Powered by PressBook Blog WordPress theme