locked
how do i show an alert box from mvc5 c# code behind RRS feed

  • Question

  • User1451609391 posted

    Hey guys I have a homecontroller and i am trying to debug with a alert box. But I cannot find out how to do this in mvc. I used to use Response.Write("js code here") in webforms. Is there anything like that in mvc? Thanks

    Friday, May 15, 2020 1:04 PM

Answers

  • User475983607 posted

    Hey guys I have a homecontroller and i am trying to debug with a alert box. But I cannot find out how to do this in mvc. I used to use Response.Write("js code here") in webforms. Is there anything like that in mvc? Thanks

    Not really.  In MVC you have total control over the HTML that returned to browser so there is not need for a special method to render JavaScript.  If you want to show an alert then simply show an alert.  There are a lot of different ways to do this below is one idea.

        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewBag.Alert = "Hello World";
                return View();
            }
        }
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    @section scripts
    {
    
        @if (ViewBag.Alert != null)
        {
            <script>
                alert("@ViewBag.Alert");
            </script>
        }
     }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 15, 2020 1:24 PM

All replies

  • User475983607 posted

    Hey guys I have a homecontroller and i am trying to debug with a alert box. But I cannot find out how to do this in mvc. I used to use Response.Write("js code here") in webforms. Is there anything like that in mvc? Thanks

    Not really.  In MVC you have total control over the HTML that returned to browser so there is not need for a special method to render JavaScript.  If you want to show an alert then simply show an alert.  There are a lot of different ways to do this below is one idea.

        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewBag.Alert = "Hello World";
                return View();
            }
        }
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    @section scripts
    {
    
        @if (ViewBag.Alert != null)
        {
            <script>
                alert("@ViewBag.Alert");
            </script>
        }
     }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 15, 2020 1:24 PM
  • User1451609391 posted

    interesting thanks alot

    Friday, May 15, 2020 1:25 PM