10

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?

4
  • 2
    ViewBag or ViewData would be better than Session. See arunprakash.co.in/2013/08/… Commented Mar 16, 2015 at 11:02
  • TEMPDATA is recommended here, it will act as a flash messenger. Commented Mar 16, 2015 at 11:06
  • @Andy that blog doesn't explain why it's "better" (nor does your comment), and the blog is just copypasta from the Q&A linked by markpsmith. Commented Mar 16, 2015 at 11:09
  • And ViewBag, ViewData and TempData. Commented Mar 16, 2015 at 11:17

1 Answer 1

29

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:

  1. TempData is a property of ControllerBase class.
  2. TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  3. It’s life is very short and lies only till the target view is fully loaded.
  4. It’s required typecasting for getting data and check for null values to avoid error.
  5. 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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.