简体   繁体   中英

JavaScript call in Razor C#

I am trying to call javascript function inside a helper method in Razor. My code looks something like that:

@helper MyMethod() 
{
     for (int i = 0; i < 5; i++)
     {
          drawMe(i)
     }
}

The drawMe function is declared in an external js file which is properly included. I have tried surrounding it with tags, using Html.Raw but nothing worked so far. Any help will be greatly appreciated.

Thanks

If you want to execute javascript like this, you need to wrap it in a script tag. In the example below, your helper output a script tag to the page and the javascript is a for loop. However, the reason this is not working for you might be something else. When you output scripts like this the browser executes it immediately, as soon as it detects it in the DOM. However, your external file might not be loaded yet.

@helper MyMethod() 
{
    <script type="text/javascript">

         for (var i = 0; i < 5; i++)
         {
              drawMe(i);
         }

     </script>
}

So to be on the safe side, you might want to defer executing your javascript until the page has finished loading all the scripts:

@helper MyMethod() 
{
    <script type="text/javascript">

        window.onload = function()
        {
            for (var i = 0; i < 5; i++)
            {
                 drawMe(i);
            }
        }


     </script>
}
@helper MyMethod() 
{
     for (int i = 0; i < 5; i++)
     {
          <text><script type="text/javascript">drawMe(@i)</script></text>
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM