How to show alert in mvc 4 controller?

I tried to show a warning window in mvc controller if-else condition. But the warning window does not appear. 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"); } } 
+10
c # asp.net-mvc-4
source share
8 answers

You cannot show a warning from the controller. There is a one-way message from the client to the server. Therefore, the server cannot tell the client to do anything. Client and server requests provide an answer.

Therefore, you need to use javascript when the response returns to show any mailbox.

OR

using jquery on a button that invokes a controller action

 <script> $(document).ready(function(){ $("#submitButton").on("click",function() { alert('Your Message'); }); }); <script> 
+10
source share
 TempData["msg"] = "<script>alert('Change succesfully');</script>"; @Html.Raw(TempData["msg"]) 
+49
source share

Use this:

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

or

 return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>"); 
+18
source share

Cannot display warnings from the controller. Because MVC views and controllers are completely separate from each other. You can only display information in a view. Therefore, it is necessary to transmit information that will be displayed from the controller for viewing using ViewBag , ViewData or TempData . If you are trying to display content stored in TempData["Message"] , you can do this on the watch page by adding a few lines of JavaScript.

 <script> alert(@TempData["Message"]); </script> 
+3
source share
 <a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');"> 
+1
source share
 Response.Write(@"<script language='javascript'>alert('Message: \n" + "Hi!" + " .');</script>"); 
0
source share

I know this is not a typical alert window, but I hope this can help someone.

This extension allows you to display notifications inside an HTML page using bootstrap.

It is very easy to implement and works well. Here is the github page for the project, including some demos.

0
source share

@ Wiki This is so simple and does its job. Well done!

0
source share

All Articles