在ASP.NET WebSite中,我们一般将公共的方法写到App_Code的类中去达到一种封装和复用。在MVC3中存在helper语法可以达到同样的目的。
先看试图View下 Share文件夹中_Layout.cshtml:
<
head
>
< title > @ViewBag.Title </ title >
< link href = " @Url.Content( " ~/ Content / Site.css " ) " rel = " stylesheet " type = " text/css " />
< script src = " @Url.Content( " ~/ Scripts / jquery - 1.5 . 1 .min.js " ) " type = " text/javascript " ></ script >
</ head >
< title > @ViewBag.Title </ title >
< link href = " @Url.Content( " ~/ Content / Site.css " ) " rel = " stylesheet " type = " text/css " />
< script src = " @Url.Content( " ~/ Scripts / jquery - 1.5 . 1 .min.js " ) " type = " text/javascript " ></ script >
</ head >
head部分对Css和Script文件的引用,其中Url.Content()将相对路径转为应用程序的绝对路径,和Server.MapPath()类似。使用helper语法如下:
@Css(
"
Site.css
"
)
@Script( " jquery-1.5.1.min.js " )
@helper Script( string scriptName)
{
< script src = " @Url.Content( " ~/ Scripts / " + scriptName) " type = " text/javascript " ></ script >
}
@helper Css( string cssName)
{
< link href = " @Url.Content( " ~/ Content / " +cssName) " rel = " stylesheet " type = " text/css " />
}
@Script( " jquery-1.5.1.min.js " )
@helper Script( string scriptName)
{
< script src = " @Url.Content( " ~/ Scripts / " + scriptName) " type = " text/javascript " ></ script >
}
@helper Css( string cssName)
{
< link href = " @Url.Content( " ~/ Content / " +cssName) " rel = " stylesheet " type = " text/css " />
}
在项目下新建app_code文件夹,在app_code中新建一个视图文件Content.cshtml,删除里面的Code,并将原Layout.cshtml中的helper部分copy
到Content.cshtml下,这是发现Url缺少引用声明。添加@using System.Web.Mvc ,并添加一个的helper参数,如下:
@using System.Web.Mvc
@helper Script(string scriptName,UrlHelper Url)
{
<script src="@Url.Content("~/Scripts/" + scriptName)" type="text/javascript"></script>
}
@helper Css(string cssName, UrlHelper Url)
{
<link href="@Url.Content("~/Content/" + cssName)" rel="stylesheet" type="text/css" />
}
这样Layout.cshtml页面就可以这样对Css和Scrpt引用了 (默认脚本放到Script文件夹中,样式文件放Content文件夹中)
<head>
<title>@ViewBag.Title</title>
@Content.Css("Site.css", Url)
@Content.Script("jquery-1.5.1.min.js", Url)
</head>
转载于:https://www.cnblogs.com/orangepoet/archive/2011/07/05/2098561.html