开发者

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

I don't necessarily need to run it at server, however, I would like to use the ~/js/somefile.js syntax.

Previously, I had just set everything with Absolute paths and set my project to be at the root level. SO, I'd just declare all my stylesheets, background images and javascript files something like /css/somefile.css

However, for this project, it doesn't run as root.

I can't put runat="server" on开发者_如何转开发 a script tag.

I can put it on a link tag, though.

This must be a common problem with a few simple answers.


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


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.


Taken from dailycoding.com:

<script language="javascript" src="<%=ResolveUrl("~/[PATH]")%>" type="text/javascript"></script> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜