开发者

Loading a view specific stylesheet in an asp.net mvc3 app?

I'm trying to load a view specific stylesheet in an asp.net mvc3 application (just learning this stuff!), so in my _Layout.cshtml I have:

<head>
<!--- All the common css & JS declarations here -->
@ViewBag.PageIncludes
</head>
<body>

Then in my controller I have:

public ActionResult Index()
        {
            ViewBag.PageIncludes = "<link rel='stylesheet' t开发者_开发问答ype='text/css' href='../Content/viewspecificstylesheet.css')' />";
            return View();
        }

However, when I view the page, even though the declaration is in the head, the text is rendered in the body, and thus rendered as text.

A couple of questions as a result:

Why, even though I declare in the head is this rendered in the body? What is the best practice for loading a specific stylesheet for a given view/controller?

Thanks


You could use sections:

<head>
    <!--- All the common css & JS declarations here -->
    @RenderSection("Styles", false)
</head>
<body>
...
</body>

and then in the Index.cshtml view:

@section Styles {
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/viewspecificstylesheet.css")" />    
}

<div>This is the index view</div>

and your controller no longer needs to worry about styles which is purely view specific responsibility:

public ActionResult Index()
{
    return View();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜