I tried show a alert box in mvc controller by if-else condition.But alert box does not display.Where is my mistake ?
Controller
public ActionResult Index()
{
int userId = Convert.ToInt32(Session["userId"].ToString());
if (WebMatrix.WebData.WebSecurity.IsAuthenticated)
{
if (userId == 90043)
{
return View();
}
else
{
TempData["Message"] = "You are not authorized.";
return RedirectToAction("Index", "Home");
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
Alert Box. Use the alert() function to display a message to the user that requires their attention. This alert box will have the OK button to close the alert box. The alert() function takes a paramter of any type e.g., string, number, boolean etc.
We can return the custom message from controller by throwing exception and handling it at client side using the ActionFailure event of the Grid. Grid Rendering Code. 2. Handle the returned message in the ActionFailure event of the Grid.
It shows on the page "@Html. Raw(ViewBag. Message)" or "@ViewBag. Message", not the actually error message.
Use this:
return JavaScript(alert("Hello this is an alert"));
or:
return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");
TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])
You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.
You therefore need to use javascript when the response returns to show a messagebox of some sort.
OR
using jquery on the button that calls the controller action
<script>
$(document).ready(function(){
$("#submitButton").on("click",function()
{
alert('Your Message');
});
});
<script>
It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag
, ViewData
or TempData
. If you are trying to display the content stored in TempData["Message"]
, It is possible to perform in the view page by adding few javascript lines.
<script>
alert(@TempData["Message"]);
</script>
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