There are four ways to pass
the 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
First to create Controller:
public class HomeController : Controller
{
// GET: Home
public ActionResult
Index()
{
return View();
}
}
Partial View:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
1.
Pass data from enclosing
View to Partial View
@{
ViewBag.Title = "Index";
double piValue = 3.14;
}
<h2>Index</h2>
@Html.Partial("_MyPartial",
piValue)
Output:
Data received is :
3.14
2. Pass data to Partial
View using ViewBag/ViewData
In controller Action
Result
public ActionResult Index()
{
ViewBag.piValue = 3.14;
return View();
}
Razor View
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Partial("_MyPartial",
(double) @ViewBag.piValue)
Output:
Data received is :
3.14
3.
Pass data to Partial View
using TempData
In controller:
public ActionResult Index()
{
TempData["piValue"] = 3.14;
return View();
}
Razor View:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Partial("_MyPartial",
(double) TempData["piValue"])
Output:
Data received is :
3.14
4.
Pass data to Partial View
using strongly typed model
In Model View
public class Employee
{
public string Name { get; set; }
public string
Location { get; set;
}
}
In controller:
public ActionResult Index()
{
//Assume we are getting below data from the database
var model
= new Employee { Name = "John", Location = "New
York" };
return View(model);
}
Razor View:
@model PassingData.Models.Employee
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Partial("_MyPartial",Model)
No comments:
Post a Comment