This is the 10thMVC (Model view controller) tutorial and in this article we will try to understand how we can improve reusability using partial views.
This is the 10thMVC (Model view controller) tutorial and in this article we will try to understand how we can improve reusability using partial views. In case you are completely new to MVC (Model view controller), do have a look at the previous articles and videos given at the end of the article.
Alternatively you can also
see these videos to come up to speed
My half-life has been spent on writing interview questions for Microsoft technology and I hope I keep writing them. You can see my video tutorial for the same by clicking on
.NET,ASP.NET,C#,MVC Interview questions and answers
When we talk about web application reusability is the key. So as a MVC developer we would like to create reusable views. For instance we would like to create reusable views like footer and header views and use them inside one big MVC view.
Reusable views can be achieved by creating “Partial views”.
Step 1:- Create a simple view
The first step would be to create a simple view with a controller. You can see from the below snapshot, I have created a simple view called as “Index.aspx” which will be invoked via “Homecontroller.cs”.
In case you are coming to this section directly please see the previous Labs to synch up.
Step 2:- Create a simple partial view
Now that we have created the main view it’s time to create a partial view which can be consumed inside the “Index” view. In order to create a partial view , right click on the view folder and mark the check box “Create a partial view” as shown in the below figure.
Step 3:- Put something in partial view
Put some text or logic in your partial view.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
This is reusable view
Step 4:- Call the partial view in the main
Finally call the partial view in the main view using “Html.RenderPartial” function and pass the view name in the function as shown in the below code snippet.
<% Html.RenderPartial("MyView"); %>
Also ensure that the partial view is in the same folder where your main view is. In case it’s not then you need to also pass the path in the “RenderPartial” function. You can see in the below figure I have moved the partial view in the main “Views” folder.
One more thing which is noticeable is that the icons for main view and partial are very different. You can see the yellow border in the partial view icon which does not exist in the main view icon.
Step 5:- Run the program and see the action.
Finally do a CNTRL + f5, put the proper controller path and see your hard work result. Below is the snapshot of how things should look like.