Overview Of Partial View In ASP.NET MVC

In this article, you will come to know about following things.

  • What is View?
  • View explanation for WebForm User
  • What is Partial View?
  • Partial View explanation for WebForm User
  • What is Html.Partial?
  • What is Html.RenderPartial?
  • What is difference between Partial vs RenderPartial?
  • Step by step implementation

What is View?

In ASP.NET MVC, View is funtionable with the help of Controller. All the incoming browser requests first come to the Controller and then the Controller will decide which action or view execute.

View For WebForm Users

In ASP.NET webform, all the incoming browser requests come to ASPX file and file execute directly on browser very easily. That's why we know which file is currenly running.

Here you should keep in mind that all incoming browser requests knock the door of controller action and that action will decide which view should be executed on board.

To understand about view step by step go through these links,

  • http://www.c-sharpcorner.com/UploadFile/2f59d0/introduction-to-mvc/
  • https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/asp-net-mvc-views-overview-cs 

What is Partial View?

This is useful for splitting the code and can be reused in different view(s). It helps to reduce duplicate coding.

There is no restriction to use partial view. We can create partial view with model without model attachement also. This help sus to work smarter and faster on project.

Partial View For WebForm User

In web form you know UserControl (ASCX file), yes this is similar kind of terminology. Partial view of MVC is the same thing as Usercontrol in WebForm. Which helps to reuse the code.

Example

  1. In e-commerce sites we have to display products list and product details; in this scenario we can use this.
  2. Club site mostly displays the member detail.

In this article we will create partial view for Member detail.

What is Html.Partial?

It generates a bunch of code of html with data or without data. It returns HTML encoded string which can be stored in variable.

What is Html.RenderPartial?

It also generates a  bunch of code of html but cannot be stored in variable. It writes content directly to the response stream that's why we call this with complete line of C#.

What is the difference between Partial vs RenderPartial?

Html.Partial return a string.

Html.RenderPartial returns void and it directly writes to the response stream.

Html.Partial is not required in C# ; line terminator is at the end.

Html.RenderPartial is required C# ; line terminator is at the end.

Please, visit this link to learn more.

Step By Step Implementation

Before we start working on project first create table named “tblMembers”.

tblMembers Structure

ASP.NET

tblMembers table SQL script

  1. /****** Object:  Table [dbo].[tblMembers]    Script Date: 07-Oct-17,Sat 4:51:48 PM ******/  
  2. SET ANSI_NULLS ON  
  3. GO  
  4.   
  5. SET QUOTED_IDENTIFIER ON  
  6. GO  
  7.   
  8. SET ANSI_PADDING ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[tblMembers](  
  12.     [MemberID] [int] IDENTITY(1,1) NOT NULL,  
  13.     [MemberName] [varchar](50) NULL,  
  14.     [MemberCity] [varchar](25) NULL,  
  15.     [MemberPhone] [varchar](15) NULL  
  16. ON [PRIMARY]  
  17.   
  18. GO  
  19.   
  20. SET ANSI_PADDING OFF  
  21. GO  

Sample data of tblMembers

ASP.NET

Start Visual Studio click on File-->New Project

project named “PartialView”

ASP.NET

Select MVC

ASP.NET

Wait for project to get loaded on solution explorer.

ASP.NET

Now Double click on Web.Confing

Web.Confing file setting for ConnectionString

  1. <configuration>  
  2.  <connectionStrings>  
  3.     <add name="ClubConnectionString" connectionString="Data Source=admin;Initial Catalog=MBkTest;Persist Security Info=True;User ID=sa;Password=clserver" providerName="System.Data.SqlClient"/>  
  4.   </connectionStrings>  
  5. </configuration>  

Right click on solution explorer -->Add-->New Item-->

ASP.NET

Named LinqToSql Classes as ClubHouseDataClasses.dbml

Click on add button. Open Server explorer and drag and drop tblMembers from server explorer to ClubHouseDataClasses DBML canvas.

ASP.NET

Double click on HomeController, create a new Method named: MemberList

This method will generate a list of members and give it to view.

  1. public ActionResult MemberList()  
  2.       {  
  3.           var db = new ClubHouseDataClassesDataContext();  
  4.           var memberList2 = db.tblMembers.ToList().AsEnumerable();  
  5.           return View(memberList2);  
  6.       }  

After writing the above code, now it's time to create a view.

Right click on MemberList method select Add View…

ASP.NET

Fill in the details of dialog box as given below.

ASP.NET

MemberList.cshtml created inside following folder,

Views-->Home-->MemberList.cshtml

At bottom of MemberList check and correct code as given below,

  1. <td>  
  2.            @Html.ActionLink("Edit""MemberEdit"new { id=item.MemberID }) |  
  3.            @Html.ActionLink("Details""MemberDetail"new {  id=item.MemberID}) |  
  4.            @Html.ActionLink("Delete""MemberDelete"new { id=item.MemberID })  
  5.        </td>   

MemberList.cshtml Code

  1. @model IEnumerable<PartialView.tblMember>  
  2.   
  3.   
  4. @{  
  5.     ViewBag.Title = "MemberList";  
  6.     Layout = "~/Views/Shared/_Layout.cshtml";  
  7. }  
  8.   
  9. <h2>MemberList</h2>  
  10.   
  11. <p>  
  12.     @Html.ActionLink("Create New""Create")  
  13. </p>  
  14. <table class="table">  
  15.     <tr>  
  16.         <th>  
  17.             @Html.DisplayNameFor(model => model.MemberID)  
  18.         </th>  
  19.         <th>  
  20.             @Html.DisplayNameFor(model => model.MemberName)  
  21.         </th>  
  22.         <th>  
  23.             @Html.DisplayNameFor(model => model.MemberCity)  
  24.         </th>  
  25.         <th>  
  26.             @Html.DisplayNameFor(model => model.MemberPhone)  
  27.         </th>  
  28.         <th></th>  
  29.     </tr>  
  30.   
  31. @foreach (var item in Model) {  
  32.     <tr>  
  33.         <td>  
  34.             @Html.DisplayFor(modelItem => item.MemberID)  
  35.         </td>  
  36.         <td>  
  37.             @Html.DisplayFor(modelItem => item.MemberName)  
  38.         </td>  
  39.         <td>  
  40.             @Html.DisplayFor(modelItem => item.MemberCity)  
  41.         </td>  
  42.         <td>  
  43.             @Html.DisplayFor(modelItem => item.MemberPhone)  
  44.         </td>  
  45.         <td>  
  46.             @Html.ActionLink("Edit""MemberEdit"new { id=item.MemberID }) |  
  47.             @Html.ActionLink("Details""MemberDetail"new {  id=item.MemberID}) |  
  48.             @Html.ActionLink("Delete""MemberDelete"new { id=item.MemberID })  
  49.         </td>  
  50.     </tr>  
  51. }  
  52.   
  53. </table>  

Now you can run your code to view how member list is appearing on screen.

ASP.NET

Your output will look like the above screen.

Now switch back to HomeController for writing Member Detail functionality. Create a new ActionMethod  named MemberDetail

  1. public ActionResult MemberDetail(int id)  
  2.        {  
  3.            var db = new ClubHouseDataClassesDataContext();  
  4.            var memberdetail = (from a in db.tblMembers where a.MemberID == id select a).FirstOrDefault();  
  5.   
  6.            return View(memberdetail);  
  7.        }  

After writing the above code, now it's time to create a view.

Right click on MemberDetail method select Add View…

ASP.NET

Fill in the details of dialog box as given below.

ASP.NET

MemberDetail.cshtml is created inside following folder,

Views-->Home-->MemberDetail.cshtml

Open MemberDeail.cshtml file and delete entire code and put the following code.

  1. @model PartialView.tblMember  
  2.   
  3. @{  
  4.     ViewBag.Title = "MemberDetail";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>MemberDetail</h2>  
  9.   
  10. <div>  
  11.    <p><i>Start of Partial View</i></p>  
  12.     @Html.Partial("_MemberDetailView",Model)  
  13.     <p><i>End of Partial View</i></p>  
  14.   
  15.      @Html.ActionLink("Edit""Edit"new { id = Model.MemberID }) |  
  16.     @Html.ActionLink("Back to List""MemberList")  
  17. </div>  

ASP.NET

Now we are going to create PartialView. Right click on Shared folder

Select  Add-->View

ASP.NET

After click on Add-->View

 This dialog will appear 

ASP.NET

Your Views folder should look like this image of Solution Explorer:

ASP.NET

_MemberDetailView.cshtml code

  1. @model PartialView.tblMember  
  2.   
  3. <div>  
  4.     <hr />  
  5.     <dl class="dl-horizontal">  
  6.         <dt>  
  7.             @Html.DisplayNameFor(model => model.MemberID)  
  8.         </dt>  
  9.   
  10.         <dd>  
  11.             @Html.DisplayFor(model => model.MemberID)  
  12.         </dd>  
  13.   
  14.         <dt>  
  15.             @Html.DisplayNameFor(model => model.MemberName)  
  16.         </dt>  
  17.   
  18.         <dd>  
  19.             @Html.DisplayFor(model => model.MemberName)  
  20.         </dd>  
  21.   
  22.         <dt>  
  23.             @Html.DisplayNameFor(model => model.MemberCity)  
  24.         </dt>  
  25.   
  26.         <dd>  
  27.             @Html.DisplayFor(model => model.MemberCity)  
  28.         </dd>  
  29.   
  30.         <dt>  
  31.             @Html.DisplayNameFor(model => model.MemberPhone)  
  32.         </dt>  
  33.   
  34.         <dd>  
  35.             @Html.DisplayFor(model => model.MemberPhone)  
  36.         </dd>  
  37.   
  38.     </dl>  
  39. </div>  

Now change the RouteConfig.Cs file which is located inside AppStart folder.

  1. public static void RegisterRoutes(RouteCollection routes)  
  2.         {  
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.             routes.MapRoute(  
  6.                 name: "Default",  
  7.                 url: "{controller}/{action}/{id}",  
  8.                 defaults: new { controller = "Home", action = "MemberList", id = UrlParameter.Optional }  
  9.             );  
  10.         }  

I had made MemberList actionmethod as default action method of application.

Now it's time to Run Application by pressing F5.

Output

Screen 1

ASP.NET

Screen 2

ASP.NET

Thank you… Happy Coding…Enjoy


Similar Articles