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.
The runat="server" tag tells the . NET compiler to execute the tag on the server. it can be added to any html tags which make them available on server side code.
To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time.
The runat="server" tag in ASP.NET allows the ability to convert/treat most any HTML element as a server-side control that you can manipulate via code at generation time. Some controls have explicit implementations, others simply revert to a generic control implementation.
Script tags are used to add Javascript (or similar) script to the final HTML which is rendered by the browser, and hence allow client-side scripting. <% ... %> tags are ASP tags that are processed on the server side, and will not be present in the rendered HTML.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With