Partial View in MVC

23 Oct 2013, 04:28 PM

Partial view is a reusable component you want to render across multiple views. It has similar concept as user control (.ascx) in asp.net that can renders inside the multiple views. It helps to reduce the duplication and you can use it to render same kind of data in several places.

In this blog we will add a partial view that shows student detail.

Student Model

Add the Student class in the model and add required properties in it.

        
    public class Student
    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Address { get; set; }

        public string Designation { get; set; }

    }
    
    

Add Partial view

For adding partial view right-click on the shared folder then clicks on ‘Add’ and then ‘View’. It will open the popup window where you will provide “View” name and other settings.

It is better to start the name of partial view with “_” because it is a convention for the reusable components. You must select a checkbox “Create as a partial view” for creating partial view. If you want to bind your partial view with strong typed object then you can also select checkbox “Create a strongly-typed view”.

Press add button to create new partial view. In the newly added view design the page as per your requirement.

 @model MvcRecursivePartialView.Models.Student

 <div>
    Id: @Html.DisplayFor(x=>Model.Id)
 </div>

 <div>
    First Name: @Html.DisplayFor(x=>Model.FirstName)
 </div>

 <div>
    Last Name: @Html.DisplayFor(x=>Model.LastName)
 </div>
    

Pass Model from controller

The parent view that contains the partial view should pass Model for partial view in it. In this example we are passing Student model for it.

 public ActionResult Student()
 {

    var item = new Student();

    item.Id = 1;
    item.FirstName = "Michel";
    item.LastName = "Johnson";

    return View(item);
 }

    

Add Main View

Create a view for the Student() method in the controller and add the partial view using in it @Html.Partial().

 @model MvcRecursivePartialView.Models.Student
 
 @{
    ViewBag.Title = "Student";
 }

 <h2>Student</h2>

 @Html.Partial("../Shared/_studentList", Model)

    

@Html.Partial() has 4 overloaded methods

  • Partial(string partialViewName);
  • Partial(string partialViewName, object model);
  • Partial(string partialViewName, ViewDataDictionary viewData);
  • Partial(string partialViewName, object model, ViewDataDictionary viewData);
About Blog
This Article Explains the Partial View in MVC.

Date 23 Oct 2013, 04:22 PM
Views 2,081
;