TempData Tutorial with example in MVC (Model-View- Controller)

TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects. It is dictionary type which is derived from TempDataDictionary.
Note: Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors.
TempData  Example:-


On View Page:-
Here I have created ViewTempMessage name.
@{
    Layout = null;
}
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @TempData["Message"];
    </div>
</body>
</html>
On Controller Page:-
Here I have created TempData name. Here I have call View that name is ViewTempMessage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Controllers
{
    using System;
using System.Collections.Generic;

using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Controllers
{
    public class ViewTempController : Controller
    {

        public ActionResult index()
        {
         

            TempData["name"] = "Neeraj Srivastava";
            TempData["age"] = 26;

            return RedirectToAction("ViewTempMessage");
        }
        string Name;
        int Age;
        public ActionResult ViewTempMessage()
        {
   
            if (TempData.ContainsKey("name"))
                Name = TempData["name"].ToString();

            if (TempData.ContainsKey("age"))
                Age = int.Parse(TempData["age"].ToString());

            TempData["Message"] = ""+ Name +" is age "+ Age +" old";
           

            return View();
        }
    }

}
TempData Tutorial with example in MVC (Model-View- Controller) TempData Tutorial with example in MVC (Model-View- Controller) Reviewed by NEERAJ SRIVASTAVA on 11:38:00 PM Rating: 5

No comments:

Powered by Blogger.