我们开发网站项目的时候,都会遇到这样的问题:就是页面怎么统一风格,有一致的外观,在之前ASP.NET的时代,我们有两种选择,一个是使用MasterPage页,一个是手动,自己在每个页面写CSS样式,但这样代码量太大了。。不可取,那么到了ASP.NET MVC时代,有什么技术可以统 ...
我们开发网站项目的时候,都会遇到这样的问题:就是页面怎么统一风格,有一致的外观,在之前get='_blank'>ASP.NET的时代,我们有两种选择,一个是使用MasterPage页,一个是手动,自己在每个页面写CSS样式,但这样代码量太大了。。不可取,那么到了ASP.NET MVC时代,有什么技术可以统一页面风格呢???有,那就是Layout布局视图。下面就开始学习吧。
1. 首先使用空模板,新建一个MVC Web项目:
新建完成之后,初始化状态是:
2.接着在根目录【LayoutMVC这里是】下,新建一个文件夹【Content】,在里面添加一个css文件,取名【Site.css】
3.在【Views】文件夹下,新建一个【Shared】文件夹,在Shared文件夹下,新建一个Layout布局页
布局页:
<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @*Url.Content将虚拟路径转化为应用程序的绝对路径 *@ <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" /></head><body> <header> <div class="content-wrapper"> <div class="float-left"> <p class="site-title"> @Html.ActionLink("Code Express", "Index", "Home") </p> </div> <div class="float-right"> <nav> <ul id="menu"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> </ul> </nav> </div> </div> </header> <div id="body"> @RenderSection("featured", required: false) <section class="content-wrapper main-content clear-fix"> @RenderBody() </section> </div> <footer> <div class="content-wrapper"> <div class="float-left"> <p>© @DateTime.Now.Year – Code Express</p> </div> </div> </footer></body></html>In this layout we are using a HTML helper method and some other system defined methods so let's see these methods one by one. 在布局页里面,我们使用了HTML帮助类的方法,和其他一些系统定义的方法,我们来分别看看这些方法。
URL。Content方法,是UrlHelper类中的方法,它可以把虚拟【相对】路径转化为应用程序的绝对路径,它有一个
string类型的参数,也就是文件的虚拟路径。如果这个路径没有以~波浪线开头,然后这个方法就会返回一个固定路径,Html.ActionLink(): The easiest way to render an HTML link in is to use the HTML.ActionLink() helper. HTML.ActionLink方法,这是最简单的方法,来做一个HTML链接。在MVC中HTML.ActionLink不是链接到视图,而是链接到控制器的方法,ActionLink是HTMLHelper类的扩展方法。RenderSection是WebPageBase类中的方法,我们可以在布局页中使用它来,作为一个占位符,就和ASP.NET中类似,有两个参数,一个是名字,一个是Required,Required设置为True的时候,我们在视图中就一定要添加这个块,否则运行的时候,报错。RenderBody(): In layout pages, renders the portion of a content page that is not within a named section. It returns the HTML content to render. RenderBody is required, since it's what renders each view.RenderBody是加载显示,不在RendSection代码快中的内容,RenderBody是必须要的。_ViewStart文件,指定了使用的布局页,如果没有的话,你就需要在每个视图中手动,添加
原标题:MVC学习系列5
关键词:mvc
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。