ViewBag, ViewData and TempData

后端 未结 8 1763
半阙折子戏
半阙折子戏 2020-11-22 04:43

Could any body explain, when to use

  1. TempData
  2. ViewBag
  3. ViewData

I have a requirement, where I need to set a value in a control

相关标签:
8条回答
  • 2020-11-22 05:49

    TempData in Asp.Net MVC is one of the very useful feature. It is used to pass data from current request to subsequent request. In other words if we want to send data from one page to another page while redirection occurs, we can use TempData, but we need to do some consideration in code to achieve this feature in MVC. Because the life of TempData is very short and lies only till the target view is fully loaded. But, we can use Keep() method to persist data in TempData.

    Read More

    0 讨论(0)
  • 2020-11-22 05:50
    void Keep()
    
    Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
    
        @model MyProject.Models.EmpModel;
        @{
        Layout = "~/Views/Shared/_Layout.cshtml";
        ViewBag.Title = "About";
        var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
        TempData.Keep(); // retains all strings values
        } 
    
    void Keep(string key)
    
    Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
    
        @model MyProject.Models.EmpModel;
        @{
        Layout = "~/Views/Shared/_Layout.cshtml";
        ViewBag.Title = "About";
        var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
        TempData.Keep("emp"); // retains only "emp" string values
        } 
    
    0 讨论(0)
提交回复
热议问题