Difference between TempData keep() And Peek() in Asp.Net MVC

Introduction :

TempData helps to maintain data when we want to transfer data from one action method to another action method of the same or a different controller as well as redirects.

I have already discussed what is TempData and why and when to use TempData in previous article .

Now learn what is difference between TempData keep() and TempData peek().

keep() Mehod:

public class codelernerController : Controller
{
public ActionResult Index()
{
TempData[“KeepMessage“] = “TempData.keep() example in mvc”;
return View();
}
}

View :

<h2>@TempData[“KeepMessage“] </h2>

@{

TempData.Keep(“KeepMessage“);

}

Keep() method marks the specified key in the dictionary for retention

You can use Keep() when prevent/hold the value depends on additional logic.

when you read TempData  one time and want to hold data for next request then use keep method, so TempData can available for next request as above example.

peek() Mehod:

public class codelernerController : Controller
{
public ActionResult Index()
{
TempData[“peekMessage“] = “TempData.peek() example in mvc”;
return View();
}
}

View :

<h2>@TempData.Peek(“PeekMessage“) </h2>

@{

// TempData.Peek(“PeekMessage”);   don’t need to keep

}

Peek() method returns an object that contains the element that is associated with the specified key, without marking the key for deletion

Using Peek method both the operation of accessing and persisting value is done in a single Call/statement.

Using Tempdata peek method we can perform read and hold data for next request in single call.

Conclusion :

keep method is used when need to hold data for next request, by using peek method we can read and hold data for next request  in single call.

SEE MORE

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *