[c#] How to show alert message in mvc 4 controller?

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");
    }
}

This question is related to c# asp.net-mvc-4

The answer is


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>

I know this is not typical alert box, but I hope it may help someone.

There is this expansion that enables you to show notifications inside HTML page using bootstrap.

It is very easy to implement and it works fine. Here is a github page for the project including some demo images.


<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">

Use this:

return JavaScript(alert("Hello this is an alert"));

or:

return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</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>

TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])

Response.Write(@"<script language='javascript'>alert('Message: 
\n" + "Hi!" + " .');</script>");