ASP.NET MVC > Partial view

Call a partial view that accepts Model as parameter in ASP.NET MVC

How to call a partial view that accepts Model as parameter?


To demonstrate this, let’s first create a Controller action method.

CONTROLLER CODE

public ActionResult IndexWithPartialView()
        {
            var data = db.PersonalDetails.ToList();
            return View(data);
        }

Above action method is returning collection of PersonalDetails to the View.

VIEW OF THE ABOVE ACTION METHOD

@model IEnumerable<MVCTraining5.Models.PersonalDetail>

@{
    ViewBag.Title = "IndexWithPartialView";
}

<h2>Index With PartialView</h2>

@Html.Partial("_ListPersonalDetail", Model)

Above view accepts the collection as Model that is passed to the _ListPersonalDetail partial view by calling @Html.Partial method in the 2nd parameter.

PARTIALVIEW CODE

(_ListPersonalDetail.cshtml)

@model IEnumerable<MVCTraining5.Models.PersonalDetail>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.IsActive)
        </th>
     </tr>

     @foreach (var item in Model)
     {
         <tr>
             <td>
                 @Html.DisplayFor(modelItem => item.FirstName)
             </td>
             <td>
                 @Html.DisplayFor(modelItem => item.LastName)
             </td>
             <td>
                 @Html.DisplayFor(modelItem => item.Age)
             </td>
             <td>
                 @Html.DisplayFor(modelItem => item.IsActive)
             </td>
         </tr>
     }
</table>

Above partial view accepts collection passed in @Html.Partial method and loops through each item in the list and renders record no the web page.

 Views: 33975 | Post Order: 54



Write for us






Hosting Recommendations