Partial View In MVC C#

A Partial View is a Razor markup file (.cshtml) without an that renders HTML output within another markup file (another view).

Partial Views are used to:

  • Break up large markup files into smaller components.
  • Reduce the duplication of common markup content across markup files.

Don’t use Partial views to maintain common layout elements. Common layout elements should be specified in _Layout.cshtml files.

Don’t use a partial view where complex rendering logic or code execution is required to render the markup.

Demo For Partial View as below :

Employee.cs :

namespace PartialView.Models
{
    public class Employee
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public decimal Salary { get; set; }
    }
}

DefaultController.cs :

using Microsoft.AspNetCore.Mvc;
using PartialView.Models;

namespace PartialView.Controllers
{
    public class DefaultController : Controller
    {
        public IActionResult Index()
        {
            List<Employee> li = new List<Employee>();
            li.Add(new Employee { EmpId = 1, EmpName = "Jubin", Salary = 25000 });
            li.Add(new Employee { EmpId = 2, EmpName = "Nishit", Salary = 39000 });
            li.Add(new Employee { EmpId = 3, EmpName = "Minal", Salary = 24000 });
            li.Add(new Employee { EmpId = 4, EmpName = "Virang", Salary = 31000 });
            li.Add(new Employee { EmpId = 5, EmpName = "Mudra", Salary = 30000 });
            return View(li);
        }
    }
}

Index.cshtml :

@model IEnumerable<PartialView.Models.Employee>
@{
    ViewData["Title"] = "Index";
}
<h1>Index</h1>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EmpId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmpName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Salary)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <partial name="_ShowEmpData" model="item" />
        }
    </tbody>
</table>

Using the “partial” Tag-Helper we can call a partial view on another view.

<partial name="_ShowEmpData" model="item" />

In the “name” attribute give the partial view name. In the “model” attribute we can pass data into the partial view.

To add partial view select the “Create as a Partial view” checkbox from the Add new View Window.

_ShowEmpData.cshtml :

@model PartialView.Models.Employee
<tr>
    <td>
        @Html.DisplayFor(modelItem => modelItem.EmpId)
    </td>
    <td>
        @Html.DisplayFor(modelItem => modelItem.EmpName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => modelItem.Salary)
    </td>
</tr>

Output :

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories