views:

340

answers:

3

I have a ViewPage within which I would like to specify an external style sheet. The style sheet only applies to elements in the ViewPage. After some unsuccessful attempts I settled on using "Url.Content" as follows:

<asp:Content ID="cssLinkContent" ContentPlaceHolderID="CssLinkContent" runat="server">
    <link rel="stylesheet" type="text/css" href="<%= Url.Content("~/Content/custom.css")%>" />
</asp:Content>

This works fine at run time, but the error "The class or CssClass value is not defined" is displayed by the Visual Studio editor. I presume this is because Visual Studio cannot resolve the external style sheet when I use "Url.Content".

Any thoughts on a solution that will successfully resolve the URL at runtime and make Visual Studio happy?

Thanks in advance.

+5  A: 

I would just ignore Visual Studio. It's a great tool, but sometimes it tries to hard. Are you sure that's an error or a warning? I know it's a sucky answer, but it's what I do.

Won't it complain about styles used simply as jQuery fodder as well?

As an aside, you might want to write an Html.Stylesheet helper to encapsulate the markup and url parsing behavior, as follows:

public static string Stylesheet(this HtmlHelper Html, string url) { return Html.Stylesheet(url, null); }
public static string Stylesheet(this HtmlHelper Html, string url, string media)
{
    UrlHelper Url = new UrlHelper(new RequestContext(Html.ViewContext.HttpContext, Html.ViewContext.RouteData));
    string html = "<link type=\"text/css\" rel=\"stylesheet\" href=\"{0}\" {1}/>";
    if (!string.IsNullOrEmpty(media))
        media = "media=\"" + media + "\"";

    return string.Format(html, Url.Content(url), media);
}

Resulting in this, much cleaner, markup:

<%= Html.Stylesheet("~/Content/custom.css") %>
Stuart Branham
A: 

Did you try

<link rel="stylesheet" type="text/css" 
    href="<%= ResolveUrl("~/Content/custom.css")%>" />
blu
I am not sure why this was marked down. It works without VS warnings and without extra (unneeded) code. It also works for images and js files.
blu
-1: Yes but it leaves us with CSS class warnings in the IDE.
Jim G.
+3  A: 

It is a weird solution but it works:

<!-- next line only for VS -->
<% if(false) { %><script src="../../Content/custom.css" type="text/javascript"></script><% } %>
<link rel="stylesheet" type="text/css" href="<%= Url.Content("~/Content/custom.css")%>" />

You can also use something like this for jQuery intellisense in your Views:

<% if(false) { %><script src="../../static/jquery/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script><% } %>
eu-ge-ne
Thanks. This works. But the Microsoft Visual Studio team should know that this hackery is required and they should endeavor to *fix* the problem.
Jim G.