我正在学习ASP.NET MVC 3框架.在我的布局页面(_Layout.cshtml)中,我想有条件地包含一些CSS样式表,具体取决于控制器的名称.我怎么做?
您可以使用以下属性获取当前控制器名称:
ViewContext.RouteData.GetRequiredString("controller")
Run Code Online (Sandbox Code Playgroud)
所以根据它的价值你可以包括或不包括样式表:
@if (ViewContext.RouteData.GetRequiredString("controller") == "somecontrollername")
{
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
}
Run Code Online (Sandbox Code Playgroud)
或者使用自定义助手:
public static class CssExtensions
{
public static IHtmlString MyCss(this HtmlHelper html)
{
var currentController = html.ViewContext.RouteData.GetRequiredString("controller");
if (currentController != "somecontrollername")
{
return MvcHtmlString.Empty;
}
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var link = new TagBuilder("link");
link.Attributes["rel"] = "stylesheet";
link.Attributes["type"] = "text/css";
link.Attributes["href"] = urlHelper.Content("~/Content/Site.css");
return MvcHtmlString.Create(link.ToString(TagRenderMode.SelfClosing));
}
}
Run Code Online (Sandbox Code Playgroud)
在布局中简单地说:
@Html.MyCss()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2194 次 |
| 最近记录: |