I am new to ASP.NET and am trying to convert a web application from using hard-coded deployment locations (ie, /base/path/index.aspx) to discovering them at runtime. If I use Response.Redirect(), I can express the path as '~/index.aspx' and, at runtime, ASP.NET will build the correct URL to send the redirect to based on where the web application is deployed.
There are places in the code where Javascript and/or HTML is generated dynamically and sent to the client as part of the response to force a new window. In these cases, I don't know how to get the actual URL that should be opened in the new window. Using ~ doesn't work in this case since the URL is being evaluated by the browser and not the server. Is there a class or method in ASP.NET that will give me the URL I am looking for? I'd look myself, but I don't even know how to properly phrase my question.
The VirtualPathUtility class is what you are looking for.
Specifically you can use these methods:
VirtualPathUtility.ToAbsolute("~/");
VirtualPathUtility.ToAppRelative("~/");
You could do something like this:
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
var url = '<%= ResolveUrl("~/path/some_page.aspx") %>';
window.open(url, 'name');
</script>
</head>
<body>
<form id="form1" runat="server"></form>
</body>
</html>
Tilde (~) is basically a shortcut to HttpRuntime.AppDomainAppVirtualPath.
You can use Request.ApplicationPath and build your way to the page.
Related
I want to create a new file type (for example .jsrender). Inside this file, there is some JavaScript code, but also some code nuggets like <%= txt1.ClientID %> that have to be rendered before it's outputted.
How can I achieve this functionality? Also, how can I reference it? Can I do the following?
<script type="text/javascript" src="scripts/myjs.jsrender" runat="server" />
Will it work?
Also, I am going to reference it from code-behind file like below:
ScriptManager.RegisterStartupScript(
this.Page,
typeof(Page),
"JQueryUITimepickerAddonAjaxminJs",
String.Format("<script src='{0}' type='text/javascript' defer='defer'></script>",
ResolveUrl("~/Scripts/timepicker_addon/jquery-ui-timepicker-addon.ajaxmin.jsrender")),
false);
Do you think it will be rendered before it's outputted?
I know that we can create HttpModules for IIS, but I don't know what to do for this kind of functinality.
Thanks!
You just need to map that file extension to the ASP.Net handler. See the post below for doing that. Also look at his recommendation to use a rewrite to to just change the file extension dynamically.
How do I process .asp extensions using the .Net handler?
I have a server control that needs to programmatically inject a JavaScript reference into the page. It is to reference Microsoft's Bing map control which requires &s=1 to be appended to the script URL for use over SSL. The problem is that the .NET Framework encodes the attributes and changes the & to an & (verified with Reflector). At some point after that the & is removed altogether.
Desired script tag:
<script type="text/javascript"
src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1">
</script>
Attempt 1:
var clientScriptManager = this.Page.ClientScript;
if (!clientScriptManager.IsClientScriptIncludeRegistered(this.GetType(), "BingMapControl"))
{
clientScriptManager.RegisterClientScriptInclude(
this.GetType(), "BingMapControl",
"https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1");
}
Attempt 2:
HtmlGenericControl include = new HtmlGenericControl("script");
include.Attributes.Add("type", "text/javascript");
include.Attributes.Add("src",
"https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1");
this.Page.Header.Controls.Add(include);
Any ideas?
Desired script tag:
<script type="text/javascript"
src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1">
</script>
Actually, no. In fact, your desired script tag is:
<script type="text/javascript"
src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1">
</script>
You do want the & to be encoded as &. Why? Because the HTML standard says so. See, for example, Section C.12. Using Ampersands in Attribute Values (and Elsewhere) of the XHTML 1.0 standard:
In order to ensure that documents are compatible with historical HTML user agents and XML-based user agents, ampersands used in a document that are to be treated as literal characters must be expressed themselves as an entity reference (e.g. "&"). For example, when the href attribute of the a element refers to a CGI script that takes parameters, it must be expressed as http://my.site.dom/cgi-bin/myscript.pl?class=guest&name=user rather than as http://my.site.dom/cgi-bin/myscript.pl?class=guest&name=user.
Out of curiosity... is this code just an example? I generally only use RegisterClientScript and its ilk if there is some dynamic portion that needs to be set at runtime. Otherwise, you can just write it statically in an aspx, ascx, or js file.
Have you tried a Literal control? I know I've done this very thing recently. I'll have to dig up my code.
It seems like all controls added to Header are html.encode-d
Page.Header.Controls.Add
Quick solution is to add a property ScriptUrl
public string ScriptUrl
{
get
{
return "https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1";
}
}
and in aspx
<head runat="server">
<title></title>
<script type="text/javascript" src="<%= ScriptUrl %>"></script>
</head>
And that's all
How can I send parameters (with QueryString) within a javascript tag as the source attribute to a ASP.NET page?
Example: <script language="javascript" src="myDomain/myPage.aspx?id=123&no=43"></script>
And what I have to do in "myPage.aspx"?
For example I want to send a picture to the script tag according to it's src querystring.
The script tag is used to include javascript code in the page. If you want to show an image on the page, even one generated dynamically, you want to use an img tag, not a script tag.
<img src="myDomain/myPage.aspx?id=123&no=43" alt="some text" />
Normally, you'd use an HttpHandler for this (ashx instead of aspx) and it would simply need to construct the image (or read it from a file) and then send the data down in the response with the correct MIME-type, length, etc.
See this reference on how to retrieve images from a DB using an HttpHandler.
It's not clear what you intend to do in your myPage.aspx. Since it is a script tag, it should be generating javascript code. But I don't see any reason why you'd need to dynamically generate your javascript code. Javascript variables basically have global scope, so define the image in a variable before including the script tag.
So in your html page you would do something like this in your header:
<script type="text/javascript">
var imageURL = 'http://www.google.com/intl/en_ALL/images/logo.gif';
</script>
<script src="myScript.js" type="text/javascript"></script>
And then in myScript.js:
alert("The image URL is: " + imageURL);
//do whatever processing with the image that you need to do...
Google Analytics used to work like this (before they went to a more object-oriented approach).
Why would you send a picture to a script tag? Basically what you have will work client side. In MYPage.aspx you need to output what you want to send.
I'd recommend using an HttpHandler which is a great to dynamically provide things like CSS, Javascript or images
Asp.net System.Web.HttpContext.Current.Session null in global.asax
What's the best way to display an image from a sql server database in asp.net?
All you have to do is give your <SCRIPT> tag a SRC attribute pointing to an ASPX page, just like you wanted. The only trick is that you have to have the ASPX page that returns javascript set the contentType to text/javascript. (Make sure it sends back only valid javascript.)
Here are two files to prove that it works:
JavascriptLibraryTester.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="JavascriptLibraryTest.js.aspx?Color=red" type="text/javascript" charset="utf-8">
</script>
</head>
<body>
show Server Generated Javascript
</body>
JavascriptLibraryTest.js.aspx
<%# Page Language="C#" %>
<%
Response.ContentType = "text/javascript";
string color = Request["Color"];
string now = DateTime.Now.ToString();
%>
function showServerGeneratedJavascript(){
alert('<%=now %>\n<%=color %>');
}
I'm trying to add a script reference to jQuery in my master page so that it will work for any page. It currently looks like this
<script type="text/javascript" src="jquery.js"></script>
The problem is that the path is always relative to the executing aspx page so this will only work if the "jquery.js" file is located in the same folder. To make it work I have to change the line to:
<script type="text/javascript" src="../../jquery.js"></script>
This is obviously less than ideal because it will only work for pages that are two levels deep from the root folder. If I try the following, IIS throws an error about an unexpected character.
<script runat="server" type="text/javascript" src="~/jquery.js"></script>
Any ideas?
EDIT: I forgot to mention as well that the script MUST be in the head tag
The current top answer throws a "ASP.NET Ajax client-side framework failed to load." error when I add it to my master page. Its thrown from javascript and not the .Net compiler. If I move the ScriptManager to the head section where it should be I get a compile error about the ScriptManager needing to be inside a form tag.
The third answer throws a "Illegal characters in path." exception from the compiler
EDIT 2: When I add that line to my head tag I get this error from IIS.
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
SOLVED: I took the edited response from the answer below and put it inside an asp:ContentPlaceHolder element
You could use a ScriptManager:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/jquery.js" />
</Scripts>
</asp:ScriptManager>
EDIT: If you absolutely need this in your <head> section, you could do something like:
<head>
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/jquery.js") %>"></script>
</head>
EDIT 2: According to the comments, if you are observing that
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
you may need to change the above to use the data-binding syntax:
<head>
<script type="text/javascript"
src="<%# Page.ResolveClientUrl("~/jquery.js") %>"></script>
</head>
Try <%# instead of <%= in Master page under head section
<script type="text/javascript"
src="<%# ResolveUrl("~/YourScriptFolder/YourJQueryOrJavascript.js") %>">
</script>
Then in Code Behind of Master page under Page_Load Event
Page.Header.DataBind();
Now you are good to go with either jQuery and JavaScript as well as CSS just you need to change your path in ResolveUrl which file you want to handle CSS, JavaScript, jQuery.
If you're not going to us asp:ScriptManager or absolute paths then you can do it like this:
<script runat="server" type="text/javascript"
src='<%= Page.ResolveUrl("~/jquery.js") %>'></script>
I do not know whether you guys found the solution to your problem or not. I was facing the same problem and going nuts to figure out why do I get "jQuery is undefined" error on the plugins i use. I tried all the solutions i get from the internet but no luck at all.
But, suddenly something splash on my mind that may be the script files should be in order. So, I moved the jquery referece to first position and everything start working like charm.
Remember guys, if you're using any plugins with jquery, make sure you use the folloing order of setting reference to those fiels.
reference to the jquery library
reference to the other subsequent plug-in libraries and so on...
e.g.:
"script src="js/jquery-1.3.2.min.js" type="text/javascript"...
"script src="js/jqDnR.min.js" type="text/javascript"...
"script src="js/jquery.jqpopup.min.js" type="text/javascript"...
"script src="js/jquery.bgiframe.min.js" type="text/javascript"...
Always make sure you must put the jquery reference to first and then the subsequent libraries.
Hope, this solves your problem especially when you use with MasterPages. Its very strange that it works no matter what order you use when you don't use MasterPages but when you do, then it somehow requres the proper order.
Good luck and happy coding,
Vincent D'Souza
Look at How to Run a Root “/”. This should fix all your issues regarding unresolved .js file paths. You basically reconfigure the VS Dev server to run your application as localhost:port/ as opposed to the regular localhost:port/application name/ making name resolution work the same way as it does on IIS.
For absolute path of the file for any page use it following:
<script type="text/javascript" src="<%= Page.ResolveClientUrl("~/jquery.js") %>"></script>
<script type="text/javascript" src="/full/path/to/jquery.js"></script>
If this script tag goes directly to the browser, then you unlikely can substitute your site's root there. At least not on the server. So you can:
Deploy site to the root of domain
name and use absolute paths
(simplest solution).
Insert this
link with server control.
Preprocess resulting HTML before
sending it to the client (with
HttpResponse.Filter).
You can also use <base> HTML tag:
<base href="http://www.domain.com"></base>
and then all the links in header section are relative to base address:
<script type="text/javascript" src="scripts/jquery.js"></script>
It's often useful when you have multiple publishing destinations, like local dev web server, demo server, etc. You just replace that base URL.
<body>
<script language="javascript" src='<%= this.ResolveClientUrl("~/full/path/to/jquery.js") %>' type="text/javascript"></script>
</body>
This may be a painfully simply question for which I will be mocked but I am having difficulty in using filepaths in master pages. I believe this is because if a page in a sub-directory to using the master page then the filepath is incorrect.
To fix this I need to get the filepath from the root but I can't seem to get it working.
I tried:
<script type="text/javascript" src="~/jQueryScripts/jquery.js"></script>
and
<script type="text/javascript" src="../jQueryScripts/jquery.js"></script>
No luck on either!
Any ideas on how I can tell it to get the filepath from the root?
I'm just assuming by filepath, you actually mean url (or uri, I forget which one is partial).
Without the ~, the first example should work. <script type="text/javascript" src="/jQueryScripts/jquery.js"></script> would cause the browser to request http://www.example.com/jQueryScripts/jquery.js (where www.example.com is your domain).
I believe you need to have runat=server in the <head> tag of the MasterPage for this URL rebasing to work.
<head runat="server">
First off the tilde in front is a asp.net thing for use in server controls and won't work in basic HTML.
Without getting into detailed explanations you could just use a slash (/) in front, and include the web app name if its not the root site.
Or you could put code in your master page for dynamically including scripts, and let it handle the pathing. Like:
public void AddJavascript(string javascriptUrl)
{
HtmlGenericControl script = new HtmlGenericControl("script");
script.Attributes.Add("type", "text/javascript");
javascriptUrl += "?v" + Assembly.GetExecutingAssembly().GetName().Version;
script.Attributes.Add("src", ResolveUrl(javascriptUrl));
Page.Header.Controls.Add(script);
}
The above code also appends the assembly version. I use this mostly for development so my javascript files get updated whenever I build.
You could use the Page.ResolveUrl method to get around this
for example:
<script type="text/javascript" src="<%=Page.ResolveUrl("~/jQueryScripts/jquery.js")%>"></script>