Click here to Skip to main content
15,880,608 members
Articles / Web Development / HTML

Work with Partial view in MVC framework

Rate me:
Please Sign up or sign in to vote.
4.91/5 (16 votes)
21 Sep 2014CPOL4 min read 108K   2.9K   24   21
Work with Partial views in Asp.net MVC

Introduction

As the complexity of a web application grows, we must decide when to create a new items and when to reuse them, if possible :). Doing so keeps the application as simple and maintainable as possible. There for we should have a basic knowledge of the layout and design structure of Html pages.

Descriptions

Like Master pages(web farms) or Layout(asp.net mvc) which offer a helpful way to reuse portion of markup and maintain a consistent look and feel through out multiple pages in our site. But sometimes a scenario comes which may require more focused approach to display some high level information in the multiple location but not in all places. To achieve this functionality Asp.net MVC framework comes with solutions of Partial View, which lets you separate control of part of the page from the whole page, thus enabling us to drop in consistent functionaltiy across multiple pages without having to rewrite code.

Partial views are views that contain targeted markup designed to be rendered as part of a large view. It does not specify any layout. or we can say Partial views are the MVC replacement for user controls from ASP.NET Web Forms.

Lets go in details:

In this section, we will show you how to create and use partial views, explain how they work, and demonstrate the techniques available for passing view data to a partial view.

We can create two type of partial view

1. Empty Partial View - When Creating Partial Views, if none of the Scaffold Template option is selected, then it will create an empty partial view.

Later if we want to use model then we can attach like below syntax

C++
@model ApplicationName.Models.ModelName

2. Strongly Typed Partial View - When creating partial view, if we select or enter a type for the Model Class option then it will create strongly typed partial view. Now partial view file is created and it only contains the @model tag to specify the view model type. Then we have to pass view model objects when the partial view is rendered.

C++
@model ApplicationName.Models.ModelName

Render Partial view using Razor syntex

1. @Html.Partial ("PartialViewName", modelName)

2. @{ Html.RenderPartial("PartialViewName", modelName); }

In the both cases first parameter is the name of the partial view and second paramter is the model name (not mandatory), when second parameter is not specified, it defaults to the model in the view from which the Html.Partial() helper was called.

@Html.Partial() - it produces a fragment of HTML, rather than a full Html document. Partial helper return MVCHtmlString and renders the partial view as an Html-encoded string.

@Html.RenderPartial- it doesnot return HTML markup like most other helper methods, instead it writes content directly to the response stream, which is why we must call it like a complete line of C# using a semicolon (;).

Both way can be used to render partial view as part of view, only bit difference is performance. RenderPartial is more efficeint than Partial

Render partial view from Controller

Controller.PartialView() - it creates a PartialViewResult object that renders a partial view. The PartialViewResult renders only the markup in the view itself and does not render any layout or master page that the view may specify. Since partial pages do not execute the layout, you may have to include some dependencies, such as css or Javascript, directly in the partial view rather than including them in the page's layout.

Lets demonstrate

1. Create a demo web project to demonstrate partial view. File → New Project → Select Asp.net MVC framework and name your project and select location.Image 1

And Select Project Template and Razor as view Engine

Image 2

And Project structure is

Image 3

2. Create Home controller in controller folder, follow below snap.Image 4

And create HomeController with empty MVC controller template.Image 5

And write the below code in home controller

C++
public ActionResult Index()
{
    var model = new Company();
    model.Department = GetDepartmentList();
    return View(model);
}

public List<department> GetDepartmentList()
{
    var model = new List<department>();
    for (var count = 1; count <= 5; count++)
    {
        var data = new Department();
        data.DepartmentName = "IT " + count;
        data.DepartmentRule = "Rule " + count;
        data.AdminComment = "Admin omment " + count;
        model.Add(data);
    }
    return model;
}

public PartialViewResult ShowPartailView()
{
    return PartialView("_MyView");
}

3. Create model class -> right-click on model folder and Add-> select class then create a model class. Image 6

 public class Department
{
    public string DepartmentName { get; set; }
    public string DepartmentRule { get; set; }
    public string AdminComment { get; set; }
}

public class Company
{
    public List<department>  Department { get; set; }
}

4. Create a new folder in named as Home under Views folder and create a Index view Image 7

and copy below code

@model PartialViewDemo.Models.Company

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
        <div>
            <h1>This is from main view upper.</h1>
        </div>
        <div>
            @Html.Partial("_MyPartialView", Model.Department )
            @{
                Html.RenderPartial("_MyPartialView", Model.Department);
            }
        </div>
        <div>
            <h1>This is from main view lower.</h1>
        </div>
        <div id="divTest">
        </div>
        <input type="button" value="Click" id="btnClick"/>
</body>
    <script src="~/Content/jquery-1.7.1.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $('#btnClick').click(function(data) {
                $.post("@Url.Action("ShowPartailView", "Home")", function(data) {
                    if (data) {
                        $('#divTest').append(data);
                    }
                });
            });
        });
</script>
</html>

<meta content="width=device-width" name="viewport" /> <title></title>

5. Create a new folder named as shared under Views folder - the partial view , layout or master pages are stored in shared folder because these are shareable and can be used repeatedly. And then add two partial view (i) _MyPartialview and MySecondPartialView. Image 8

copy below code in _MyPartialView

C++
@model List<PartialViewDemo.Models.Department>
<h6> This below table content is from partial view</h6>
@if (Model != null)
 {
     <div>
         <table cellspacing="0"width="50%" border="1">
                <thead>
                 <tr>
                     <th>
                         Department Name
                     </th>
                     <th>
                         Department Rule
                     </th>
                     <th>
                         Admin Comment
                     </th>
                 </tr>
             </thead>
              <tbody>
                 @foreach (var dept in Model)
                 {
                     <tr>
                         <td align="center">
                             @dept.DepartmentName
                         </td>
                         <td align="center">
                             @dept.DepartmentRule
                         </td>
                         <td align="center">
                             @dept.AdminComment
                         </td>
                     </tr>
                 }
             </tbody>
       </table>
     </div>
 }

And in the _MySecondPartial.cshtml

C++
<h3> Testing for partial view</h3>

Now we are done with our coding part. Let debug this. Run And check.

Please download the demo to check.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionREAL example helps me understand Pin
Fei Meng28-Jan-16 19:46
Fei Meng28-Jan-16 19:46 
QuestionNice Artical we can add pratial view by click button but if we want on singal click of typeview want submit all patial view data it it possible Pin
Member 110825916-Nov-15 21:44
Member 110825916-Nov-15 21:44 
QuestionGreat work! Pin
skippyV20-Oct-15 5:08
skippyV20-Oct-15 5:08 
GeneralMy vote of 5 Pin
khanzzirfan11-Apr-15 14:15
khanzzirfan11-Apr-15 14:15 
QuestionExcellent Work done :) Pin
Shatyamm Kumar6-Oct-14 7:12
Shatyamm Kumar6-Oct-14 7:12 
AnswerRe: Excellent Work done :) Pin
khem thapa6-Oct-14 20:41
khem thapa6-Oct-14 20:41 
GeneralRe: Excellent Work done :) Pin
Shatyamm Kumar6-Oct-14 20:45
Shatyamm Kumar6-Oct-14 20:45 
QuestionVery Good... :) Pin
Jnyanendra6-Oct-14 6:58
professionalJnyanendra6-Oct-14 6:58 
AnswerRe: Very Good... :) Pin
khem thapa6-Oct-14 20:39
khem thapa6-Oct-14 20:39 
GeneralNice work..Well done Pin
Sagar kshetri1-Oct-14 3:33
professionalSagar kshetri1-Oct-14 3:33 
GeneralRe: Nice work..Well done Pin
khem thapa1-Oct-14 3:41
khem thapa1-Oct-14 3:41 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)23-Sep-14 22:39
Shemeemsha (ഷെമീംഷ)23-Sep-14 22:39 
GeneralRe: My Vote 5 Pin
khem thapa25-Sep-14 0:20
khem thapa25-Sep-14 0:20 
QuestionNice details Pin
Imran Abdul Ghani22-Sep-14 19:51
Imran Abdul Ghani22-Sep-14 19:51 
AnswerRe: Nice details Pin
khem thapa22-Sep-14 20:17
khem thapa22-Sep-14 20:17 
GeneralNice Pin
Dukhabandhu Sahoo22-Sep-14 5:59
professionalDukhabandhu Sahoo22-Sep-14 5:59 
GeneralRe: Nice Pin
khem thapa22-Sep-14 20:15
khem thapa22-Sep-14 20:15 
QuestionDownloadlink Pin
Member 1064557922-Sep-14 3:19
Member 1064557922-Sep-14 3:19 
AnswerRe: Downloadlink Pin
khem thapa22-Sep-14 3:30
khem thapa22-Sep-14 3:30 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun22-Sep-14 0:20
Humayun Kabir Mamun22-Sep-14 0:20 
GeneralRe: My vote of 5 Pin
khem thapa22-Sep-14 1:11
khem thapa22-Sep-14 1:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.