Send message when redirecting to view in ASP.NET MVC

I have an ASP.NET MVC online store with two views:

  • Product page (photo, description, etc.)
  • The form in which the user can leave a review

After the user successfully submits the form, he should be redirected back to the position page, and a one-time message should be displayed at the top: "Your review has been sent successfully."

The controller code (simplified) is as follows:

[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 several requirements to satisfy:

  • The message should not be displayed again if the user refreshes the item page.
  • The message should not pollute the URL.
  • Controller methods cannot be combined into one.

I was thinking about saving a message in a user session and discarding it after display, but could there be a better solution?

+6
source share
1 answer

Using tempdata strong>, you can transfer a message or data (string / object) from one page to another and act only from one action to another.

Some key points about tempdata:

  • TempData is a property of the ControllerBase class.
  • TempData is used to transfer data from the current request to a subsequent request (means redirecting from one page to another).
  • His life is very short and lies only until the target view is fully loaded.
  • Typing is required to obtain data and checking for null values ​​to avoid errors.
  • It is used to store only one-time messages, such as error messages, check messages. To save data using TempData, see this article: Saved 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"); } 

On the watch page:

  @TempData["message"]; //TempData["message"].ToString(); 
+13
source

Source: https://habr.com/ru/post/983861/


All Articles