ViewBag, ViewData and TempData

后端 未结 8 1876
半阙折子戏
半阙折子戏 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:39

    TempData

    Basically it's like a DataReader, once read, data will be lost.

    Check this Video

    Example

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            TempData["T"] = "T";
            return RedirectToAction("About");
        }
    
        public ActionResult About()
        {
            return RedirectToAction("Test1");
        }
    
        public ActionResult Test1()
        {
            String str = TempData["T"]; //Output - T
            return View();
        }
    }
    

    If you pay attention to the above code, RedirectToAction has no impact over the TempData until TempData is read. So, once TempData is read, values will be lost.

    How can i keep the TempData after reading?

    Check the output in Action Method Test 1 and Test 2

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            TempData["T"] = "T";
            return RedirectToAction("About");
        }
    
        public ActionResult About()
        {
            return RedirectToAction("Test1");
        }
    
        public ActionResult Test1()
        {
            string Str = Convert.ToString(TempData["T"]);
            TempData.Keep(); // Keep TempData
            return RedirectToAction("Test2");
        }
    
        public ActionResult Test2()
        {
            string Str = Convert.ToString(TempData["T"]); //OutPut - T
            return View();
        }
    }
    

    If you pay attention to the above code, data is not lost after RedirectToAction as well as after Reading the Data and the reason is, We are using TempData.Keep(). is that

    In this way you can make it persist as long as you wish in other controllers also.

    ViewBag/ViewData

    The Data will persist to the corresponding View

提交回复
热议问题