How can I use runat=“server” on a script tag in asp.Net

别等时光非礼了梦想. 提交于 2019-12-03 23:40:59
David

What I've always done is use a normal script tag and put the src in <% %> tags, as illustrated here:

<script language="javascript" src='<%=ResolveUrl("~/App_Themes/MainTheme/jquery.js")%>' type='text/javascript'></script>

You can use the ScriptManager for this:

<asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/js/somefile.js" />
        </Scripts>
</asp:ScriptManager>

You can use functions inside the path string, though, e.g.

<script type="text/javascript"
        src="<%=Url.Content("~/Scripts/jquery-1.4.2.min.js") %>"></script>

However that's the ASP.NET MVC syntax for local paths - I can't remember the forms version off the top of my head.

You can get fully what you want by wrapping script tag with asp:ContentPlaceHolder and the you can access it from code behind, for example set will it be executed or not by setting visible property to true or false. Here is the example:

    <asp:ContentPlaceHolder runat="server" ID="PrintPreviewBlock" Visible="false">
    <script id="PrintPageCall" type="text/javascript" >
        $(function() {
            window.print();
        });
    </script>
</asp:ContentPlaceHolder>

and from code behind:

PrintPreviewBlock.Visible = true;

Taken from dailycoding.com:

<script language="javascript" src="<%=ResolveUrl("~/[PATH]")%>" type="text/javascript"></script> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!