What is Partial View

Partial view is a view which can be rendered from another view which is called parent view or it can also be called as individual page. It behaves like user control which we used in asp.net. After creating a partial view, we can render this partial view in parent view as well as can also use it as individual view.

In this example we will call partial view from another view and in next article I will show how partial view can be called as individual view.

The major advantage of partial view is that we can reuse the partial view logic.

Example of Partial View

Suppose I want to create a page in which I want to show the user data in a particular format then instead writing the code in my parent view, we will put this code into partial view and call it from the parent view.

To create partial view open visual studio and add mvc project, now go to the view folder. Right click on it and add view

Note: - in this example I am using LINQ to SQL to generate backed. If you are new please read the previous section scaffolding using LINQ.

		
		Partial view in mvc
		Figure 1
		
		

In this example I have created a partial view which is type strongly and I used scaffold detail to show the data.

Now add index view and make it strongly type so that we can pass model data to the partial view at the partial view calling time.

		
		Partial view in MVC

		Figure 2
		
		

As you can see that I choose scaffold empty.

Now call the partial view from index view in the following manner:-

Index.cshtml

		
@model MvcApplication1.Models.student

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    Data from Partial view

    <div>
        @Html.Partial("_studentData",Model)
    </div>
</body>
</html>


		
		

As you can see that we call partial view and also pass model data as partial view is using this data.

In index action we also pass this data to the index view from home controller using Index action, which is as follows:-

		
		public ActionResult Index()
        {
           
 DataContext dc = new DataContext("Data Source=isha;Initial Catalog=scaffolding;User ID=isha123;Password=techaltum");
            
student stu = dc.GetTable<student>().Single(x => x.stu_id == 1);
            return View(stu);
        }

	
		

Now execute this code and see the result

		
		
		Partial view result
		Figure 3
		
		

As we can see that it’s showing data. We have written this code in partial view and just called this partial view from index view.

Note: - I have added my partial view in Home folder which created against my home controller. It can also be added in shared folder.

Email Address

For any query you can send mail at info@techaltum.com
Thanks