Click here to Skip to main content
15,909,091 members
Articles / .NET
Tip/Trick

Different Ways to Pass Data to Partial View

Rate me:
Please Sign up or sign in to vote.
4.00/5 (6 votes)
20 Apr 2015CPOL4 min read 362.1K   13   7
In this tip, you'll learn about different ways to pass data to partial view

Introduction

Partial views are just Views which you can reuse across your ASP.NET MVC application. If you are from ASP.NET Web Forms background, you can think of Partial View as User Control. Partial views can contain anything – HTML elements for displaying the data or getting the input from the users. In this tip, we are going to see the different ways to pass data to partial view for displaying data to the partial view.

As views are like partial views, you can pass data to partial view as though passing data to the view. Below are few of the methods which you can pass data to Partial View.

  1. Pass data from enclosing View to Partial View
  2. Pass data to Partial View using ViewBag/ViewData
  3. Pass data to Partial View using TempData
  4. Pass data to Partial View using strongly typed model

Before discussing about each of the methods in detail, let us talk about creating the application.

Create ASP.NET MVC project using Microsoft Visual Studio Express 2013 for the web – choosing Empty template and checking MVC as type of project. Create a Controller by name HomeController and Index action method would be added by default as below.

C#
public class HomeController : Controller
{
  // GET: Home
  public ActionResult Index()
  {
    return View();
  }
}

Right click inside the Index action method and select “Add View” from the contextual menu – This will add Index.cshtml with the following content:

HTML
@{
   ViewBag.Title = "Index";
}
<h2>Index</h2>

Create a Partial View by right clicking the Views\Shared folder and select Add -> MVC 5 Partial Page (Razor) from the contextual menu.

Image 1

I name this partial view as _MyPartial.cshtml as by convention, name of the partial view would start with underscore(_).

We are done with the setup. Let us discuss each one of the above mentioned methods for passing data to partial view in detail now.

1. Pass Data from Enclosing View to Partial View

You can initiate a variable in View using Razor and pass that variable to Partial View. I’ve made couple of changes in Index.cshtml.

  1. Creating a variable piValue of type double
  2. Calling PartialView by passing the newly created variable piValue to @Html.Partial method. @Html.Partial is the helper method for displaying the partial View
HTML
@{
   ViewBag.Title = "Index";
   double piValue = 3.14;
}

<h2>Index</h2>
@Html.Partial("_MyPartial", piValue)

In the partial view (_MyPartial.cshtml), I can consume the passed variable value by accessing @Model variable.

Data received is: @Model

When you run the application, you’ll get the following result:

Data received is : 3.14

2. Pass Data to Partial View using ViewBag/ViewData

You can use ViewData/ViewBag to pass the information from the controller’s action method to the View. ViewData uses ViewDataDictionary and ViewBag is just a wrapper around ViewData using dynamic feature.

In the below Index action method, I am passing the piValue value from action method to the View.

C#
public ActionResult Index()
{
  ViewBag.piValue = 3.14;
  return View();
}

In the View(Index.cshtml), I am passing the piValue to the partial view. The important point to note here is that @Html.Partial method does not accept the dynamic value – so we need to cast it to the actual type.

HTML
@{
   ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Partial("_MyPartial", (double) @ViewBag.piValue)

There is no change in the way the Partial View consumes your passed data. As far as Partial view is concerned, it is receiving a data which you can access through @Model.

Data received is : @Model

When you run the application, you’ll get the same result:

Data received is : 3.14

3. Pass Data to Partial View using TempData

TempData is another way to pass the data from controller’s action method to View. Tempdata persists the data even in the case of redirection whereas ViewBag/ViewData would not be able to. You can use TempData just like you use ViewData – even though the underlying behavior is different.

Below is the Index action method- where I’ve used TempData to pass data.

C#
public ActionResult Index()
{
  TempData["piValue"] = 3.14;
  return View();
}

We are passing the data to the Partial View from the TempData. There is no need to cast the data as it’s not using dynamic feature like ViewBag.

HTML
@{
   ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Partial("_MyPartial", (double) TempData["piValue"])

As usual, there is no change in the way the Partial view consumes your data.

Data received is : @Model

4. Pass Data to Partial View using Strongly Typed Model

To pass the strongly typed model, we need to have the model first. Right click Model folder and Add class file – I have named it as Employee.cs.

It’s a simple class with couple of properties – Name and Location.

C#
public class Employee
{
  public string Name { get; set; }
  public string Location { get; set; }
}

I have created instance of this class and pass it to the View. In the real world, we would be getting the value from database. 

C#
public ActionResult Index()
{
   //Assume we are getting below data from the database
   var model = new Employee { Name = "John", Location = "New York" };
   return View(model);
}

We need to make couple of changes here – first, we need to hint the View what type of data is passed to the View so that we can take advantage of intellisense and strong typing and secondly, we can just use Model keyword to pass the data to the Partial View.

HTML
@model PassingData.Models.Employee

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.Partial("_MyPartial",Model)

In Partial view as well, we need to inform what type of data we are passing to it. Then, we can access the properties of the class using @Model

HTML
@model PassingData.Models.Employee

Name : @Model.Name<br/>

Location : @Model.Location

Thanks for your reading the tip. If anything is not clear, please let me know the in the comments section. I’ll reply and update the tip as needed.

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWays to pass data to partial view Pin
Tahir7766726-Jan-20 16:05
professionalTahir7766726-Jan-20 16:05 
QuestionTime to review our dialects - "I’ve made.." , "I name this..." Pin
Cipherc24-Mar-18 21:23
Cipherc24-Mar-18 21:23 
The article is pretty awesome,
but we have to limit these dialects in our articles, "I".. for example.,
I name this partial vie..
I’ve made couple of changes.. 
Tutorials, books, magazines etc., used to have "We", "We will.." or "Let's name it.. " kind of usage for the similar scenarios, as that is more inclusive.
Nevertheless, your work is pretty good!

A constructive criticism.
Questionhow to access partial view defined in one project into another project Pin
Prajesh Talpade4-Jan-18 19:07
Prajesh Talpade4-Jan-18 19:07 
QuestionPassing data from view to partial view. Pin
Muhammad Babar22-Dec-16 19:43
Muhammad Babar22-Dec-16 19:43 
QuestionThank you! Pin
MarcusCole683321-Jul-16 4:01
professionalMarcusCole683321-Jul-16 4:01 
QuestionRegarding passing data from helper class to any partial view Pin
Member 1198024329-Mar-16 19:46
Member 1198024329-Mar-16 19:46 
QuestionCan you please help me to know how to pass data from partial view to Enclosing Parent view? Pin
Member 1102381231-May-15 21:40
professionalMember 1102381231-May-15 21:40 

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.