Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Javascript from Razor View

How can I call a Javascript method from a razor view?

At first I tried

@if (TempData["myMessage"] != null)
{ 
    @:displayMessage();
}

and when the page rendered I literally saw "@:displayMessage(); on my HTML page.

So then I tried.

@if (TempData["myMessage"] != null)
{ 
    <script type="text/javascript">displayMessage();</script>
}

Which works if displayMessage function exists on that html page. However in my case displayMessage exists in a seperate javascript file. (Which gets included on this web page)

like image 929
John Doe Avatar asked Sep 26 '22 05:09

John Doe


1 Answers

The JavaScript you're trying to call will be called when this part of the page you're rendering is rendered. Your displayMessage function may or may not be loaded at the time, depending on whether you are loading it from a separate js file, whether the script source referencing it is below the current script tag you're trying to call it from, etc. You can defer the call until the window is loaded like this:

@if (TempData["myMessage"] != null)
{ 
    <script type="text/javascript">
         window.onload = function () {
             displayMessage();
         };
    </script>
}
like image 125
Konstantin Dinev Avatar answered Sep 29 '22 07:09

Konstantin Dinev