Overlooking something basic here but I am trying to set a variable and have it print in several places on the page.
code behind:
public string myVariable { get {return "40"; } }
page:
<link rel="stylesheet" type="text/css" href="/css/main.css?v=<%=myVariable%>" />
output:
<link rel="stylesheet" type="text/css" href="/css/main.css?v=<%=myVariable %>" />
It seems to have something to do with the quotes as this works when I take it outside of the href. I find that it works fine if I place a string in the code segement.
This works, but isn't what I want:
<link rel="stylesheet" type="text/css" href="/css/main.css?v=<%="40"%>" />
What is the logic behind this behavior and what do I need to do to make it work? I would also settle for a more elegant method of doing this.
You need to single quote the html attribute like so:
<link rel="stylesheet" type="text/css" href='/css/main.css?v=<%=myVariable%>' />
I use this all the time especially within repeaters when I want to create anchor tags
<a href='PageToLinkTo.aspx?id=<%# DataBinder.Eval(Container.DataItem, "Id")%>'>Link Text</a>
This will only work in the body of your aspx page. If you have the link tag in the head section of your aspx page then check out this question for more info: Problem in Expression tag to bind string variable
Why don't you just do like this:
<link rel="stylesheet" type="text/css" <%= ("href='/css/main.css?v=" + myVariable + "'") %> />
I actually had this same issue today and solved it by using a custom code expression builder.
Your code will look something like this:
<link rel="stylesheet" type="text/css" href="/css/main.css?v=<%$ Code:myVariable%>" />
A good tutorial that I used can be found here which I was able to modify to fit my application. This will also work if you need to add code inside of a server side control.
It was really easy to implement.
Here's what I added to my web.config:
<compilation debug="true">
<expressionBuilders>
<add expressionPrefix="Code" type="CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
And in my App_Code folder I created ExpressionBuilder.vb:
Imports Microsoft.VisualBasic
Imports System.Web.Compilation
Imports System.CodeDom
<ExpressionPrefix("Code")> _
Public Class CodeExpressionBuilder
Inherits ExpressionBuilder
Public Overrides Function GetCodeExpression(ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, ByVal context As ExpressionBuilderContext) As CodeExpression
Return New CodeSnippetExpression(entry.Expression)
End Function
End Class
That was all I did to get it to work.
Try this:
<link rel="stylesheet" type="text/css" href=<%="/css/main.css?v="+myVariable %> />
AFAIK, the whole property must be a code block, like:
href='<%= "css/main.css?v=" + myVariable %>'
Related
Can anyone tell me why this works:
<script type="text/javascript" src="/js/jqFuncs.js?v=<%=jqFuncsScriptlastWriteTime %>" />
But this doesn't
<link type="text/css" rel="stylesheet" href="/css/site.css?v=<%=sitecsslastWriteTime %>" />
My code behind has:
public string jqFuncsScriptlastWriteTime = System.IO.File.GetLastWriteTime(#"c:/web/cs3/js/jqFuncs.js").ToString("yyMMdd");
public string sitecsslastWriteTime = System.IO.File.GetLastWriteTime(#"c:/web/cs3/css/site.css").ToString("yyMMdd");
The rendered HTML looks like this:
<script type="text/javascript" src="/js/jqFuncs.js?v=131126" ></script>
<link type="text/css" rel="stylesheet" href="/css/site.css?v=<%=sitecsslastWriteTime %>" />
The problem is caused by the way ASP.NET treats LINK tags. Here is another question/answer that provides the solution:
Problem in Expression tag to bind string variable
I would try adding runat="server" first on the link tag. If that does not work, then I would use the other solution that is the accepted answer.
Hie Gordon,
There are some differences between href and src. More details here:
Difference between SRC and HREF
Thanks!
For anyone else searching for the answer i used this:
<%= String.Format("<link type=\"text/css\" rel=\"stylesheet\" href=\"/css/site.css?v={0}\" />", sitecsslastWriteTime) %>
I have this really strange problem. I have written a HtmlHelper...
public static class MaterResourceLocationHelper
{
public static HtmlString GetMasterLocation(this HtmlHelper htmlHelper)
{
return new
HtmlString(ConfigurationManager
.AppSettings["MasterResourceLocation"]);
}
}
When I put the following on an MVC2 View...
<%= Html.GetMasterLocation() %>
In the view source I get...
http://localhost/esd.myapp.com/
However as soon as I try to use it in context like this...
<link href='<%= Html.GetMasterLocation() %>
/Css/jquery-ui-1.8.2.custom.css'
rel="stylesheet" type="text/css" />
I get this in the view source...
<link
href="../../Views/Shared/%3C%25=%20Html.GetMasterLocation()%20%25%3E%20/Css/jquery-ui-1.8.2.custom.css"
rel="stylesheet" type="text/css" />
Im really confused as to why that happens?
The ASP view engine has some funny rules around when these tags get evaluated and when they don't. Try this:
<link href='<%= Html.GetMasterLocation() + "/Css/jquery-ui-1.8.2.custom.css"%>'
rel="stylesheet" type="text/css" />
It seems like the <%= %> tags only get evaluated if they represent the entire HTML attribute. Otherwise the engine just treats it literally. What you're seeing here is not HTML-encoding of the result, but URL encoding of the literal value between quotes.
I'm working on a web interface in ASP.NET. If it matters, I'm using the XHTML 1.0 Transitional doctype.
This website has a masterpage thing going, and that's where the problem came in. When I used a real absolute path for the CSS link in the header, everything was fine. But then when I tried to switch it to tilde notation, all the styling broke.
Here's a fragment of the original master page, which worked fine:
<head>
<title>Account Information</title>
<link href="/css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
...
</body>
But then we found out that this account thing is going to be an application that doesn't live on the server root, so we had to make changes.
<head>
<title>Account Information</title>
<link runat="server" href="~/css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
...
</body>
Now, those same changes (adding runat="server" and a tilde) worked just FINE everywhere else in the page, but this one didn't. When I looked at the output, it was not resolving the tilde, so the link was actually pointing at "myserver.net/~/css/main.css", which obviously isn't going to work.
Next I tried using ResolveURL, like so:
<link runat="server" href="<% =ResolveURL("~/css/main.css") %>" rel="stylesheet" type="text/css" />
Visual Studio wouldn't even compile that. It didn't even know what ResolveURL meant (as a test, I stuck the same code several other places, including the page title right there next to the link tag, and it worked fine everywhere else).
I did eventually get it to work by giving the link an ID and setting the href in the code-behind:
--Master page--
<link id="StyleLink" runat="server" rel="stylesheet" type="text/css" />
--Masterpage codebehind file--
StyleLink.Attributes.Add("href", ResolveUrl("~/css/main.css"));
But I'm left wondering why I had to spend two hours fighting with this. Why didn't the standard ~ notation work in the first place? I googled around for a while but I couldn't find anything particularly relevant; the closest I could find was a discussion of ~ notation failing when it was in a sub-master page.
This works in the Master Page in front of me right now:
<head runat="server">
<link runat="server" href="~/styles/main.css" rel="stylesheet" type="text/css" />
</head>
For a Page in the root of the application, this translates out to the HTML as this:
<link href="styles/main.css" rel="stylesheet" type="text/css" />
For a Page in a folder off the root, here's what it looks like:
<link href="../styles/main.css" rel="stylesheet" type="text/css" />
(Both pages use that Master, obviously)
Alternative approach
Store the path to the CSS file in the web config, and alter it upon deployment.
You can even use Web Config Transformations to change it automatically based on the build type.
I am guessing that this may be a problem with the scope of the application. In other words when you run <link rel='stylesheet' href='~/css/base.css' id='id' runat='server'> the application may be returning something like this
http://www.mydirectory.com/includes/masterpages/css/base.css
and you want a return something like this
http://www.mydirectory.com/css/base.css
since the ~ gets the application root directory and appends it you may be getting an error on where you master page is if it is not saved in the root directory.
Here's a link to a SO question that I referenced to explain the problem.
slash(/) vs tilde slash (~/) in style sheet path in asp.net
I have no idea why it wouldn't compile other than a possibly unclosed quotation mark in the link tag ie. <link type='text/css" href="..." runat="server" /> notice the single quote in the type vs. the double quote close. I have done that on occasion but I am just guessing here. I checked it on my and dropping in the ~ with a runat server doesn't cause a compile time error for me.
I had links to CSS files in the master page using the following syntax
<link href="~/bm/Styles/Site.css" rel="stylesheet" type="text/css" />
The path resolved correctly in Chrome and Firefox, but not in IE9. The following syntax works fine in all three browsers. Notice the id and runat entries.
<link id="siteCss" runat="server"
href="~/bm/Styles/Site.css" rel="stylesheet" type="text/css" />
Currently, I have a Site.Master page for my MVC app that renders great when run directly from VS2008. It looks like this:
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../../Content/css/layout1_setup.css" />
<link rel="stylesheet" type="text/css" href="../../Content/css/layout1_text.css" />
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
</head>
Unfortunately, when used on my IIS 6.0 server in a "Virtual Directory", the CSS reference fails to load and the page fails to render properly. (By virtual directory, I mean something like http://localhost/MyTestSite where "MyTestSite" is the Virtual Directory created in IIS Manager on the server where the MVC app is installed.)
The MVC app runs fine and the HTML produced from it loads normally, but the server seems to be unable to find the location of the CSS and related images referenced. I find this baffling since it seems to work just fine when run from VS2008.
I did find a workaround to my issue, but I'm not exactly satisfied with the results:
<link rel="stylesheet" type="text/css" href=<%= Page.ResolveUrl(#"~/Content/css/layout1_setup.css") %> />
<link rel="stylesheet" type="text/css" href=<%= Page.ResolveUrl(#"~/Content/css/layout1_text.css") %> />
Using Page.ResolveUrl() feels like a hack to me as it breaks the rendering of the Split and/or Design view of page when editing in VS2008. (And all CSS tags are underlined in green as "not existing".) That said, it renders just fine in both IIS6 and VS2008 when "running".
Is there a better way to fix this problem?
EDIT: My problem sounds like the issue described here: http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx -- But I already have the fix for the default.aspx.cs file implemented as shown below.
public void Page_Load(object sender, System.EventArgs e)
{
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
// Setting "false" on the above line is supposed to fix my issue, but it doesn't.
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
<link href="<%= Url.Content("~/Content/css/mystyle.css") %>"
rel="stylesheet" type="text/css" />
Edited:
After giving this some thought I relized that when using the VS 2008 you are probably using debug mode when running the website under "ASP.Net Development Server" And when you deploy to IIS you have probably published the code in Release Mode.
If this is the case then you can try the following:
<% #if DEBUG %>
<link rel="stylesheet" type="text/css" href="../../Content/css/layout1_setup.css" />
<link rel="stylesheet" type="text/css" href="../../Content/css/layout1_text.css" />
<% #else %>
<link rel="stylesheet" type="text/css" href="<%= Url.Content("~/Content/css/layout1_setup.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Url.Content("~/Content/css/layout1_text.css") %>" />
<% #endif %>
Now with this when you run in Visual Studio 2008 your code completion tools for CSS will work as well as running your website (as a Release version) inside a virtual directory.
John Hartsock is on to something, but the preprocessor commands he is trying to execute does not work as expected in design mode (I think it actually tries to do both). You can instead try to check against a .NET Site property that is available to test if you run in design mode or not (in release configuration, the Site property is not always populated, so you also have to check if it is not null).
Also Visual Studio design viewer does not know of domain and virtual app path, so in the designer you can use / to point to app root.
<% if (Site != null && Site.DesignMode) { %>
<link href="/Content/css/layout1_setup.css" rel="stylesheet"/>
<% } else { %>
<link href="<%= Url.Content("~/Content/css/layout1_setup.css") %>" rel="stylesheet"/>
<% } %>
I am afraid there's no elegant way of doing this. You could perform the following horrible hack to cheat the designer:
<% if (false) { %>
<!-- That's just to cheat the designer, it will never render at runtime -->
<link rel="stylesheet" type="text/css" href="../../Content/css/layout1_setup.css" />
<link rel="stylesheet" type="text/css" href="../../Content/css/layout1_text.css" />
<% } %>
<link rel="stylesheet" type="text/css" href="<%= Url.Content("~/Content/css/layout1_setup.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Url.Content("~/Content/css/layout1_text.css") %>" />
Personally I never use the designer and would never do something like this in my code but if you really need to have this design view then it could be a solution.
I mean you are working in an ASP.NET MVC project, you should be manipulating html, why care about the design view? Look at the price you should pay just to get the design view working, it's too expensive. It's faster to hit CTRL+F5 in your favorite browser to see the result of your efforts than switching all the time between code and design view.
Maybe this is obvious or I've missed something but this looks like a path issue. You are using relative paths (../../). I believe when you run something in Visual Studio, the application is the root path (ie. default.aspx in your project's main directory would be localhost:port/default.aspx). If a relative path in any page goes up too many directories (ie ../ too many times), it will be ignored and taken from the root of the website (in this case localhost:port/). For example, if your folder structure is like this:
AppRoot
styles (folder)
content (folder)
otherfiles (folder)
myfile.aspx
default.aspx
You can access the content folder from myfile.aspx by using ../content/ or, even though you shouldn't do this, by using ../../content/ This only works if AppRoot is the same as the domain root (ie. localhost:port/content/ and domain.com/content/ are the same folder).
However, if you put those files in another (virtual) folder on your web server (ie. domain.com/virtual == new AppRoot) now ../../content from domain.com/virtual/otherfiles/myfile.aspx will be referring to domain.com/content/, which is incorrect.
I hope this helps.
Just tested the following to make sure it would solve both your problems (enabling design view & resolve properly). Hope it works for you
<link rel="stylesheet" type="text/css" href="~/Content/css/layout1_setup.css" runat="server" />
<link rel="stylesheet" type="text/css" href="~/Content/css/layout1_text.css" runat="server" />
In my aspx I have this line:
<link href="<%= Request.ApplicationPath %>/css/ma/screen-ma.css" rel="Stylesheet"type="text/css" media="screen" />
which renders as:
<link href="/XFormPortal/css/ma/screen-ma.css" rel="Stylesheet"type="text/css" media="screen" />
That seems correct, right?
Then i change a single character, lets say add a space between the rel and the type attribute, so now I have the following:
<link href="<%= Request.ApplicationPath %>/css/ma/screen-ma.css" rel="Stylesheet" type="text/css" media="screen" />
Which now rendes as:
<link href="<%= Request.ApplicationPath %>/css/ma/screen-ma.css" rel="Stylesheet" type="text/css" media="screen" />
Okay, what just happend here? The inline code tag is suddenly ignored and written out as text? Because of a single space?
Can anyone explain this?
I would suggest it has something to do with the order in which expressions are parsed by the precompiler... specifically, I suspect that the omission of the space in your first example causes a particular regular expression match to fail, and you essentially escape correct parsing. Use single quotes around your href tag instead.
<link href=<%="\""+Request.ApplicationPath%>/css" rel="Stylesheet" type="text/css" media="screen"/>
Try to remove the runat="server" from the head tag..