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

后端 未结 4 1681
被撕碎了的回忆
被撕碎了的回忆 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:08

    namespace TempData.Controllers
    {
     public class HomeController : Controller
     {
        public ActionResult Index()
        {
            TempData["hello"] = "test"; // still alive
            return RedirectToAction("About");
        }
    
        public ActionResult About()
        {
            //ViewBag.Message = "Your application description page.";
            var sonename = TempData["hello"]; // still alive (second time)
            return RedirectToAction("Contact");
        }
    
    
        public ActionResult Contact()
        {
            var scondtime = TempData["hello"]; // still alive(third time)
            return View();
        }
        public ActionResult afterpagerender()
        {
            var scondtime = TempData["hello"];//now temp data value becomes null
    
            return View();
        }
    }
    

    }

    In above conversation, there is little confuse for everyone. if you look at my above code, tempdata is like viewdata concept but then it is able to redirect other view also. this is first point.

    second point: few of them are saying it maintains value till read and few of them are asking that so will it read only time? not so. Actually, you can read any number of time inside your code in one postpack before page render. once page render happened, if you do again postpack (request) means, the tempdata value becomes NULL.

    even you are requesting so many time , but the tempdata value is still alive -->this case your number of request should not read temp data value.

提交回复
热议问题