John Doe
John Doe

Reputation: 3243

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)

Upvotes: 9

Views: 17011

Answers (1)

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

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>
}

Upvotes: 9

Related Questions