The function known as alert
in JavaScript must be run on the client side, specifically by the browser.
If you are submitting a standard form and wish to display an alert when the ModelState.IsValid
condition is met, you must include this within the view returned by the index action.
To transmit data between your current action method code and the action method/view generated by a redirect response, you can utilize TempData
.
public ActionResult AddMessage(Message message)
{
If(ModelState.IsValid)
{
db.Messages.Add(message);
db.SaveChanges();
TempData["Message"] = "Saved successfully";
return RedirectToAction(“Index”);
}
else
{
return View();
}
}
In the view produced by the Index
action, you can verify the presence of TempData["Message"]
, retrieve it if present, and display it using an alert.
@section Scripts
{
<script>
@if(TempData["Message"]!=null)
{
@:alert("@TempData["Message"]");
}
</script>
}