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
  1.  Using ViewData

     ViewData Dictionary Allow you to add Data information's and that will later  be access from view.
    Check out our example

           public ActionResult ViewDataExample()
                ViewData["viewdatacontent"] = "My name is ViewData";
                ViewData["subcontent"] = "Welcome ";
                return View();
    <h2>ViewData Example</h2>
    <h1> @ViewData["viewdatacontent"]</h1>
    <h2>@ViewData["subcontent"] </h2>
    Check This example and understand ViewData ..
  2. 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();
    <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
  3. Strongly Typed view with model object
      Check this post

Jishnu Chandran

.net Developer with Web skills from previous work, and a taste for Developing web apps.

Post A Comment: