Reputation: 11
I need to display success msg when user registered. below i attached code. that code not displaying success msg. whats wrong. please help. (This is Asp.net core MVC web application)
[HttpPost]
public ActionResult Register(UserAccount user)
{
if (ModelState.IsValid)
{
_context.UserAccounts.Add(user);
_context.SaveChanges();
ModelState.Clear();
ViewBag.Message = "Successfully Registration Done";
}
return View();
}
Upvotes: 1
Views: 4981
Reputation: 239250
You shouldn't be using ViewBag
at all for this. Use TempData
instead and follow the PRG (post-redirect-get) pattern.
[HttpPost]
public ActionResult Register(UserAccount user)
{
if (ModelState.IsValid)
{
_context.UserAccounts.Add(user);
_context.SaveChanges();
TempData["Message"] = "Successfully Registration Done";
return RedirectToAction("Foo");
}
return View();
}
On success, you need to redirect the user somewhere else. It makes no sense to return them to the registration form, after they've already registered, and it solves the issue of having to clear the model state. You use TempData
to store the message, so it persists through the next request. Then, in your view:
@TempData["Message"]
Where you want it to display.
Upvotes: 1
Reputation: 569
Anywhere in your HTML page you can use the viewbag.
Example:
<h4>@ViewBag.Message</h4>
Upvotes: 5