In this post i will discuss what are the different methods for pass value from controller to view.
Basically MVC provide 3 options for passing information from an action method (controller ) to view, They are
- Using ViewData
- using ViewBag
- Using Strongly typed view with view model objects
Using ViewData
ViewData Dictionary Allow you to add Data information's and that will later be access from view.
Check out our example
Controller:
public ActionResult ViewDataExample()
{
ViewData["viewdatacontent"] = "My name is ViewData";
ViewData["subcontent"] = "Welcome ";
return View();
}
View
<h2>ViewData Example</h2>
<h1> @ViewData["viewdatacontent"]</h1>
<h2>@ViewData["subcontent"] </h2>
Check This example and understand ViewData ..ViewBag
ViewBag is different when compare ViewData ,You can it understand later Because ViewBag implement dynamic features introduce in MVC 4 versions .The basic thing in ViewBag is that properties can be added to ViewBag is Dynamically
Refer our code shown below
Controller :
public ActionResult ViewBagExample()
{
ViewBag.viewdatacontent = "My name is ViewData";
ViewBag.subcontent = "welcome";
return View();
}
View:
<h2>ViewBagExample</h2>
<h1> @ViewBag.viewdatacontent</h1>
<h2>@ViewBag.subcontent </h2>
Note: ViewBag use viewData as storage mechanism .One thing you keep in mind ,Both ViewBag and ViewData content or information is Lost after fully view rendered .
My point of view ViewBag is better then ViewData because of it is little bit Easier than ViewData- Strongly Typed view with model object
Check this post
Post A Comment:
0 comments: