Create partial view (Usercontrol) in MVC 4.

 

Introduction

In this post, I am explain how to Create partial view (Usercontrol) in MVC 4.
In web form application we use usercontrol for create reusable elements, same way in MVC we will use partial view.

Prerequisite

I used followings:
  • .Net framework 4.0
  • Entity Framework
  • Sql Server 2008

Steps :

Just follow the steps and get result easily.

Step - 1 : Create New Project

Go to File > New > Project > Select asp.net mvc4 web application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a tables and insert data for show in partial view.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example I have created a table "Population"

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add Action for render Main View.

Go To Controller > Add your action > write following code and Rebuild your application.


public ActionResult ViewWithPartial()
        {
            return View();
        }

Step-6: Add Action for render Partial View.

Go To Controller > Add your action > write following code.


public ActionResult WorldpopulationTopTen()
        {
            using (WorldPopulationEntities dc = new WorldPopulationEntities())
            {
                var v = dc.Populations.OrderByDescending(a => a.Population1).ToList();
                return PartialView("_TopTenCountry", v);
            }
        }
                                  

Step-7: Add Partial View.

Please rebuild your application before create view.

Right Click on Home(folder) under Views(Folder) > Add > View > Enter View name > Check "Create a Strongly-typed view" > Select "Model Class" > Check "Create as a partial view". > Add.
Write following Code inside your view

 
@model IEnumerable<MVCPartialView.Population>
@{
    ViewBag.Title = "_TopTenCountry";
}
<h2>Top Ten Country based on Population</h2>
<table>
    <tr>
        <th>Sl. No.</th>
        <th>Country</th>
        <th>Population</th>
        <th>Percentage(%)</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.SlNo)</td>
        <td>@Html.DisplayFor(modelItem => item.Country)</td>
        <td>@Html.DisplayFor(modelItem => item.Population1) </td>
        <td>@Html.DisplayFor(modelItem => item.Percentage)</td>
    </tr>
}
</table>

Step-8: Add View (main view).

Go To Controller > Right Click on Action (Main Action) > Add View > Enter View Name > Add.
Write following Code inside your view.


@{
    ViewBag.Title = "ViewWithPartial";
}
<h2>View With Partial</h2>
<table>
    <tr>
        <td>
            <b>View Content</b>
            <p>
                Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore
                magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl
                ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat,
                 vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent
                 luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option
                congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam;
                est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod
                ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est
                notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula
                quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
            </p>
        </td>
        <td width="400px">
           <b>Partial View Content</b>
            @{Html.RenderAction("WorldpopulationTopTen", "Home");}
        </td>
    </tr>
</table>

Step-9: Run Application.

Check your result.
For any queries please comments here. Thank You.

Download Source Code

Related Post:

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.