Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Different ways to pass data from controller to view in Asp .Net MVC

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 342
    Comment on it

    "ViewData vs ViewBag vs TempData vs Session"

    There are following four ways to pass data from controller to view in Asp .Net MVC:-

    • ViewData
    • ViewBag
    • TempData
    • Session

    Overview:

    alt text

    Let us see them in more detail:

    ViewData:

    It is a dictionary object introduced in MVC 1.0. It is used to pass data from controller to the view. It's life cycle is during the current request only. It requires typecasting for retrieving data and null value check inorder to avoid error.

    Example:

    public ActionResult Index(string student)
    {
          ViewData["Student"] = student;
          return View();
    }
    

    ViewBag:

    It is a dynamic property of ControllerBase class introduced in MVC 3.0. It is used to pass data from controller to the view. It's life cycle is during the current request only. It does not requires typecasting for retrieving data.

    Example:

    public ActionResult Index(string student)
    {
          ViewBag.Student = student;
          return View();
    } 
    

    TempData:

    It is a dictionary object introduced in MVC 1.0 used to pass data from one page to another (i.e. current request to subsequent request). It's life cycle is very short, lives till the target view is fully loaded. It requires typecasting for retrieving data and null value check inorder to avoid error.Mostly used to store error messages, validation messages,etc.

    Example:

    public ActionResult Index(string student)
    {
        TempData["Student"] = student;
        return View();
    }
    

    Session:

    It is a property of Controller class used to pass data within the ASP.NET MVC application. It's life cycle depends on its expiration time and is valid for all requests, not for a single redirect. It requires typecasting for retrieving data and null value check inorder to avoid error.

    Hope it Helps.... Happy Coding..!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: