ViewBag, ViewData, TempData, Session - how and when to use them?

后端 未结 4 1688
被撕碎了的回忆
被撕碎了的回忆 2021-02-07 10:07

ViewData and ViewBag allows you to access any data in view that was passed from controller.

The main difference between those two is the way you are accessing the data.

4条回答
  •  旧巷少年郎
    2021-02-07 11:01

    ViewBag, ViewData, TempData, Session - how and when to use them?

    ViewBag

    Avoid it. Use a view model when you can.

    The reason is that when you use dynamic properties you will not get compilation errors. It's really easy to change a property name by accident or by purpose and then forget to update all usages.

    If you use a ViewModel you won't have that problem. A view model also moves the responsibility of adapting the "M" (i.e. business entities) in MVC from the controller and the view to the ViewModel, thus you get cleaner code with clear responsibilities.

    Action

    public ActionResult Index()
    {
        ViewBag.SomeProperty = "Hello";
        return View();
    }
    

    View (razor syntax)

    @ViewBag.SomeProperty
    

    ViewData

    Avoit it. Use a view model when you can. Same reason as for ViewBag.

    Action

    public ActionResult Index()
    {
        ViewData["SomeProperty"] = "Hello";
        return View();
    }
    

    View (razor syntax):

    @ViewData["SomeProperty"]
    

    Temp data

    Everything that you store in TempData will stay in tempdata until you read it, no matter if there are one or several HTTP requests in between.

    Actions

    public ActionResult Index()
    {
        TempData["SomeName"] = "Hello";
        return RedirectToAction("Details");
    }
    
    
    public ActionResult Details()
    {
        var someName = TempData["SomeName"];
    }
    

提交回复
热议问题