Use the same CSS file for masterpage and page content - c#

I have an APS.net app (C#) with several pages that use the same MasterPage. In that page, I have included a couple stylesheets like so:
<head runat="server">
<link href="/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />
</head>
These styles apply correctly to all content that is in the actual .master file (page), but are not applied to any pages that use the Master page (for instance default.aspx uses that master page and has a Content placeholder in it).
If I add these lines in each individual page:
<link href="/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />
Then the styles show up as expected... but it was my hope that I could include them in the master page so that I didn't need to include these references in each subsequent page too.
Because these files are not located physically in the same project (they are shared between several apps), i cannot just include them as an ASP.net theme that would be applied to all pages.
Update
In order to rule out the file locations problem, I used the absolute URL for these stylesheets...
<link href="https://myserver/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="https://myserver/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />
That way, no matter where it is read from, the file can be located. This still exhibits the same behavior.
To me, it looks like the masterPage is rendered with the CSS styles (because they're in the same file) and then the child/calling page is rendered without the CSS styles (because they aren't in that file, they're in the masterPage) and then those two files are combined together (as opposed to combining them together first and THEN rendering the style elements for the combined pages). Adding to this belief was my previous example of adding the include for the CSS file in the calling page itself, which will cause it to display the CSS correctly.
You can view the source of this file, and in the head section, you can see the CSS styles linked correctly, but they aren't applied to any elements from the calling page while they are applied to all elements in the masterPage.

Is the content page in a different folder that the master? If so, you'll have to get the application relative path to the css files using ResolveUrl in the master page:
<link href='<%= ResolveUrl("~/apps/_lib/ui/styles1.css") %>' type="text/css" rel="stylesheet" />
Update: If this doesn't work, then you might have HTML or CSS errors like Lance suggested. Try using the HTML and CSS validators at w3schools.com. If it still doesn't work after fixing any errors, double check your CSS selectors with the rendered HTML as Steve suggested. ASP.Net's generated IDs have bitten me more than once.

What about this?
<link runat="server" href="~/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link runat="server" href="~/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />

What jrummell posted is what I use on my sites to ensure that the links work if I were to move my pages around.
As far as rendering. The rendering is done on the client machine's browser. To the browser it has no idea the html is generated from multiple documents.
I would make sure your HTML and CSS are correct.
On a side note i have noticed the last week or so that VS2008 keeps messing my css stylesheets up, doing really random things like moving text around. However, I think this might just be something on my machine. Just something to check.
Here is some sample code I checked this just to make sure and this works.
Head of Master Page
<head runat="server">
<link rel="stylesheet" type="text/css" href="../css/style.css" />
</head>
Content Place Holder
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="something">
Lance
</div>
</asp:Content>
Css in StyleSheet
.something{
color:Blue;
}
The result is "Lance" in Blue in the child page.

Maybe it might be your css selectors. When you add master pages, asp.net tacks on more prefixes to the ids.

I had a similar problem. As others have suggested, you should be able to use ResolveUrl to make sure the path is correct.
Unfortunately, this created a further problem for me. My head tag was runat server. My link tags were not.
The resolve url within my link tag would never execute. Instead, the C# code and response.write tags were being encoded and outputted to the page.
Bizarrely, the same technique in a script (non-runat server) tag would work as normal.
To solve the problem, I ended up writing the whole link tag within an ASP.Net Response.Write tag:
<%="<link href='" + ResolveUrl("~/apps/_lib/ui/styles.css") + "' rel='stylesheet' type='text/css' />"%>
That worked.
How strange. Somehow, it is all related to the head tag being runat sever.

It looks like you have done it correctly, so your error seems weird and sounds like maybe you've mady a typo in the master page. Try to look at the generated source (view source in the browser) of the two pages, one with the links in the master pages and one with the links in the web page, and compare the paths.

Something like this should work. You should be able to include the css in the header of the master. And then, include a ContentPlaceHolder in the header so if you need custom header stuff in your content pages you can do that. Does that not work?
<head>
<link href="/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
Ultimately you don't want a
<head></head>
tag in your content page, it's possible that is overriding your master page header.

Related

Show style even that css file is empty

I started to learn mvc, something weird happens, I have index.cshtml and inside of it I have:
<head>
...
<link href="#Url.Content("~/Content/Index.css")" rel="stylesheet" type="text/css" />
</head>
where Index.css is empty file, even that this css file is empty the page gets style, and if I comments the line like:
#*<link href="#Url.Content("~/Content/Index.css")" rel="stylesheet" type="text/css" />*#
then there is no style to the page
Probably you've your Index.css stored in some different location, it could be not visible in Solution Explorer. Try switching to Folder View and search for that css file.
Also it might be stored in bin/obj folder. In that case you can try git clean -fxd.
Probably some stylesheets or bundles are referenced in the _Layout.cshtml.
The _Layout.cshtml is per default the layout for all views so the styles and scripts referenced in it will effect your index.cshtml as well.

Masterpage and default page

I would like my default.aspx to use masterpage but have a different body than the rest of my webpages is this possible? Basically I want my default.aspx to have a background image for the entire page but still use the masterpage because I have menu and things I would like to use on that page as well. Is this possible?
You can define the styles and everything for a particular page in Content Page and not Master Page. In your case, if you want a separate styles and background for default.aspx, you can define those styles in default.aspx page.
inside of default.aspx do
<style>
BODY { background-image: url(....image here ....);}
</style>
I know it is not the nicest pattern but... cmon, masterpages
You can inline it on default.aspx
<style>
body{
/*Background stuff here */
}
</style>
or have an if on your master page
#if(currentpage == "home")
<div id="background">
</div>
#endif
or
#if(currentpage == "home")
<body style="background-stuff-here">
#else
<body>
#endif
Put these lines in you master page head section
<head>
<link type="text/css" rel="stylesheet" href="/styles/common1.css" />
<script type="text/javascript" src="/scripts/common1.js"></script>
<asp:contentplaceholder id="ExtraStylesAndScripts" runat="server" />
</head>
And these lines to you default page
<asp:content contentplaceholderid="ExtraStylesAndScripts" runat="server">
<link type="text/css" rel="stylesheet" href="/styles/extra1.css" />
<link type="text/css" rel="stylesheet" href="/styles/extra2.css" />
<script type="text/javascript" src="/scripts/extra1.js"></script>
<script type="text/javascript" src="/scripts/extra2.js"></script>
</asp:content>
Now you are free to set different page style for different content pages.
You can change background or other appearance in "styles/extra1.css" files.
A very simple solution would be a MultiView and pass in something like an enum object telling the master page what View to display. If you in the future need to add a different design for another page you can just add a View.

Why can't CSS resolve the ~ symbol in relative links on my master page?

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" />

Unable to reference CSS properly in Site.Master with MVC2 in a Virtual Directory

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" />

How to add a media attribute to the CSS LINK html tag for the ASP.NET WebResource.axd Http Handler

The ASP.NET WebResource.axd Http Handler is used to serve resources embedded in DLL's.
The LINK html tag is automatically generated by ASP.NET.
I would like to intercept the generation of the LINK html tag for a certain set of embedded CSS from a third party DLL and add a media attribute.
In summary:
I would like to add a Media attribute to the LINK html tag for the ASP.NET WebResource.axd Http Handler.
So this:
<link type="text/css" rel="stylesheet" href="/WebResource.axd?d=XXXXX" />
Appears like this:
<link media="screen and (min-device-width: 481px)" type="text/css" rel="stylesheet"
href="/WebResource.axd?d=XXXXX" />
Cheers
There is a workaround. Firstly, links like this are being added to the Page's head. Your page must have runat=”server” in the <head> tag for the automatic style sheet inclusion. The pages created by the IDE have this setting automatically. So, links being added is a HtmlLink control type. The idea is to iterate through controls in Page's header, find HtmlLink controls and set necessary attribute (or even attributes). I include this into the Page_Load event:
Page.Header.Controls
.OfType<HtmlLink>()
.ToList()
.ForEach(link =>
{
link.Attributes["media"] = "screen and (min-device-width: 481px)";
});
Before this I had:
<head id="Header">
<title></title>
<link href="App_Themes/MyTheme/main.css"
type="text/css"
rel="stylesheet" />
</head>
and after the result is:
I know, this uses Themes insted of WebResource.axd but for the last one the result will be the same.
The latest thing: there may be another links in the page. So it would be good to recognize our links (the links need to be modified). So if there is no id attribute you could recognize them by href attribute.

Categories