Pass message on redirect to view in ASP.NET MVC
18,088
By using tempdata you can pass message or data(string/object) from one page to another page and it's valid only from one action to another.
Some key points about tempdata:
- TempData is a property of ControllerBase class.
- TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
- It’s life is very short and lies only till the target view is fully loaded.
- It’s required typecasting for getting data and check for null values to avoid error.
- It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article:Persisting Data with TempData
In your controller:
[HttpPost]
public ActionResult AddReview([Bind] long id, [Bind] string text)
{
_context.Reviews.Add(new Review { Id = id, Text = text });
_context.SaveChanges();
TempData["message"] = "someMessage";
return RedirectToAction("ViewItem");
}
In your view page:
@TempData["message"]; //TempData["message"].ToString();
Author by
Impworks
Updated on July 22, 2022Comments
-
Impworks almost 2 years
I have an ASP.NET MVC online shop-like application with two views:
- An item's page (photo, description, etc.)
- A form where the user may leave a review
After the user successfully submits the form, he should be redirected back to the item's page and a one-time message should be displayed on top: "Your review has been submitted successfully".
The controller code (simplified) looks like this:
[HttpGet] public ActionResult ViewItem([Bind] long id) { var item = _context.Items.First(x => x.Id == id); return View(item); } [HttpGet] public ActionResult AddReview() { return View(); } [HttpPost] public ActionResult AddReview([Bind] long id, [Bind] string text) { _context.Reviews.Add(new Review { Id = id, Text = text }); _context.SaveChanges(); return RedirectToAction("ViewItem"); }
There are a few requirements to meet:
- The message must not show again if the user refreshes the item's page.
- The message must not pollute the URL.
- The controller methods may not be merged into one.
I was thinking of storing the message in user session and discarding it once displayed, but may be there's a better solution?