Monday, 11 August 2014

Use of TempData in MVC

Hey,
I found it very useful. TempData do just as its name said. Temporary storage for any information.
Suppose you are redirecting one controller to another controller and while redirecting you think you will pass some message or data to that controller. How will you do that? Yes, at first you will think that pass it through parameter. You are right. But if you just want to pass a simple message and for that reason you don't want to create a parameter you may use this TempData.

Let's see how we may implement it:

Public ActionResult INDEX()
{
       TempData["Message"] = "Hello, Improve your skill";
       return RedirecToAction("AnotherMethod");
}

Public ActionResult AnotherMethod()
{
       ViewBag.Information = TempData["Message"] as string;
        var model = context.getEmployeeList();
        return view("ViewName");
}


Now, In your ViewName.cshtml you can access ViewBag.Information like this-


<label>@ViewBag.Information</label>

Hope this will help...

No comments:

Post a Comment