You must Sign In to post a response.
  • Category: ASP.Net MVC

    How to maintain sessions in MVC


    this is one of the interview question which has been asked to me

    How will you implement/maintain sessions in MVC application.


  • #765232
    Following are the ways to maintain session in MVC: tempdata, viewdata, viewbag, hidden fields or HTML controls
    Temp data - Internally uses session variables to maintain data when you move from one controller to another controller or from one action to another action i.e. when you redirect.
    View data - Maintains data when you move from controller to view.
    View Bag - A dynamic wrapper around view data.Uses dynamic keyword internally.
    Hidden fields and HTML controls - Maintains data from UI to controller only. You may send data from hidden fields or hTML controls to controller using GET or POST methods.
    Hope it helps.
    Shashikant Gurav

  • #765236
    1. You can handle the session as like ASP.NET using Session key word.
    2. And also you have more option to handle the session based on your requirment

    Temp data - Between Controllers
    View data - Between Controller to view.
    View Bag - Consist of View datas.

    By Nathan
    Direction is important than speed

  • #765245

    You can maintain sessions in the following levels in MVC Architectural pattern.

    1) Temp Data -- maintain state between controller to controller.
    2) ViewData -- maintain state between controller to view
    3) ViewBag -- maintain state between view to Layout.
    4) Hidden Field/ QueryString -- maintain state between View to controller.
    5) Session -- works in all the above cases.

    Give respect to your work, Instead of trying to impress your boss.

    Blog :

  • #765253
    Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serializing them and storing them in a session. MVC is also use session variable same as ASP.NET
    checkout below snippet

    //adding data to session
    //assuming the method below will return list of Products

    var products=Db.GetProducts();

    //Store the products to a session


    //To get what you have stored to a session

    var products=Session["products"] as List<Product>;

    //to clear the session value


    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • Sign In to post your comments