Partial Views in Asp.net Core MVC

Partial Views in Asp.net Core MVC
Partial view is a reusable chunk of Razor markup (.cshtml) that can be embedded within other views. They are designed to encapsulate specific UI elements, such as lists, forms, or widgets, allowing you to avoid repeating code and maintain a more organized structure.
 
Why Use Partial Views?
Reusability: A single partial view can be used in multiple views, saving development time and reducing the potential for inconsistencies.
Modularity: Partial views help break down complex views into smaller, more manageable components, making your code easier to read and maintain.
Dynamic Content: You can pass data to partial views, making them dynamic and adaptable to different contexts.
 
 
Notes
Naming Convention: Partial views are typically named with a leading underscore (e.g., _ListPartialView.cshtml). This convention helps distinguish them from full views.
Location: By default, partial views are located in the Views/Shared folder or in the same folder as the view that uses them. You can override the default location by specifying the full path.
Rendering: You can render partial views in your main views using:
Tag Helpers: <partial name=”_ListPartialView” /> or <partial name=”_ListPartialView” model=”yourModel” />
HTML Helper: @await Html.PartialAsync(“_ListPartialView”) or @await Html.PartialAsync(“_ListPartialView”, yourModel)
 
Code Example
_ListPartialView.cshtml (Partial View)
<div class=”list-container”>
    @{
        //ViewBag.ListTitle = “Updated”; // Not recommended
    }
 
    <h3>@ViewBag.ListTitle</h3>
    <ul class=”list”>
    @foreach (string item in ViewBag.ListItems)
    {
        <li>@item</li>
    }
    </ul>
</div>
ViewBag: This example uses ViewBag to pass the ListTitle and ListItems data to the partial view. However, it is generally recommended to use a strongly typed model to pass data to partial views for better type safety and maintainability.
 
 
Views/Home/Index.cshtml (Main View)
<h1>Home</h1>
 
<partial name=”_ListPartialView” />
 
@{
    var myViewData = new ViewDataDictionary(ViewData); // Create a new ViewDataDictionary
    myViewData[“ListTitle”] = “Countries”;
    myViewData[“ListItems”] = new List<string>() { “USA”, “Canada”, “Japan”, “Germany”, “India” };
}
<div class=”box”>
    <partial name=”_ListPartialView” view-data=”myViewData” />
</div>
 
<h3>ListTitle in View: @ViewData[“ListTitle”]</h3>
 
This main view renders the _ListPartialView twice:
First Rendering:
The @ViewBag.ListTitle value in the partial view will be null (as it wasn’t explicitly set before the partial view is rendered).
The @ViewBag.ListItems will also be null and the loop will not execute.
A new ViewDataDictionary named myViewData is created.
 
Second Rendering:
The myViewData dictionary is used to pass the ListTitle (“Countries”) and ListItems (a list of countries) to the partial view.
The partial view will display the list of countries because ViewBag.ListItems is not null.
After the partial view has rendered, the ViewData[“ListTitle”] still refers to the original value (“Asp.Net Core Demo App”) set in the controller. This is because the myViewData dictionary is a separate instance of ViewDataDictionary.
 
Views/Home/About.cshtml (Main View)
<h1>About</h1>
 
<h2>About company here</h2>
<p>Lorem Ipsum is simply dummy text…</p>
@{
    await Html.RenderPartialAsync(“_ListPartialView”);
}
This view also renders _ListPartialView using the Html.RenderPartialAsync method. The result is the same as the first render in Index.cshtml.
 

Strongly Typed Partial Views
A strongly typed partial view, just like a strongly typed view, is associated with a specific model class using the @model directive. This means that the partial view has direct access to the properties and methods of that model, providing compile-time type checking and IntelliSense support within the partial view.
 
How to Use Strongly Typed Partial Views
Create a Model Class: Define a class that represents the data structure you want to pass to your partial view.
Use @model in the Partial View: Add the @model directive at the top of your partial view, specifying the model class: @model YourNamespace.YourModel.
Pass the Model: When rendering the partial view from your main view, pass an instance of your model class using the model attribute of the <partial> tag helper or the model parameter of the Html.PartialAsync method.
 
 
Code Example
ListModel.cs (Model)
namespace PartialViewsExample.Models
{
    public class ListModel
    {
        public string ListTitle { get; set; } = “”;
        public List<string> ListItems { get; set; } = new List<string>();
    }
}
This model will be used to represent the data for the list that’s rendered in the partial view.
 
 
_ListPartialView.cshtml (Strongly Typed Partial View)
@model ListModel // Specify the model type
 
<div class=”list-container”>
    <h3>@Model.ListTitle</h3>
    <ul class=”list”>
    @foreach (string item in Model.ListItems)
    {
        <li>@item</li>
    }
    </ul>
</div>
@model ListModel: This directive indicates that this partial view expects a model of type ListModel.
Access Model Properties: You can directly access properties of the model object using @Model.PropertyName.
 
Index.cshtml (Main View)
@using PartialViewsExample.Models
 
<h1>Home</h1>
 
@{
    ListModel listModel = new ListModel();
    listModel.ListTitle = “Countries”;
    listModel.ListItems = new List<string>() { “USA”, “Canada”, “Japan”, “Germany”, “India” };
}
<partial name=”_ListPartialView” model=”listModel” />
Creating the Model: An instance of ListModel is created and populated with data.
Passing the Model: The model attribute in the <partial> tag helper is used to pass the listModel to the _ListPartialView partial view.
 
About.cshtml (Main View)
@{
    ListModel listModel = new ListModel();
    listModel.ListTitle = “Programming Languages”;
    listModel.ListItems = new List<string>()
    {
    “Java”,
    “C#”,
    “Python”
    };
 
    await Html.RenderPartialAsync(“_ListPartialView”, listModel);
}
Same as the Index.cshtml, but using the Html.RenderPartialAsync HTML helper.
 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply