I have an ASP.NET MVC online shop-like application with two views:
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:
I was thinking of storing the message in user session and discarding it once displayed, but may be there's a better solution?
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:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With