Latest web development tutorials

ASP.NET MVC 頁面和佈局


為了學習ASP.NET MVC,我們將構建一個Internet 應用程序。

第3 部分:添加樣式和統一的外觀(佈局)。


添加佈局

文件_Layout.cshtml 表示應用程序中每個頁面的佈局。 它位於Views 文件夾中的Shared 文件夾。

打開文件_Layout.cshtml,把內容替換成:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<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") "></script>
<script src=" @Url.Content("~/Scripts/modernizr-1.7.min.js") "></script>
</head>
<body>
<ul id="menu">
<li> @Html.ActionLink("Home", "Index", "Home") </li>
<li> @Html.ActionLink("Movies", "Index", "Movies") </li>
<li> @Html.ActionLink("About", "About", "Home") </li>
</ul>
<section id="main">
@RenderBody()
<p>Copyright W3CSchool 2012. All Rights Reserved.</p>
</section>
</body>
</html>

HTML 幫助器

在上面的代碼中,HTML 幫助器用於修改HTML 輸出:

@Url.Content() - URL 內容將在此處插入。

@Html.ActionLink() - HTML 鏈接將在此處插入。

在本教程後面的章節中,您將學到更多關於HTML 幫助器的知識。


Razor 語法

在上面的代碼中,紅色標記的代碼是使用Razor 標記的C#。

@ViewBag.Title - 頁面標題將在此處插入。

@RenderBody() - 頁面內容將在此處呈現。

您可以在我們的Razor教程中學習關於C#和VB(Visual Basic)的Razor標記的知識。


添加樣式

應用程序的樣式表是Site.css,位於Content 文件夾中。

打開文件Site.css,把內容替換成:

body
{
font: "Trebuchet MS", Verdana, sans-serif;
background-color: #5c87b2;
color: #696969;
}
h1
{
border-bottom: 3px solid #cc9900;
font: Georgia, serif;
color: #996600;
}
#main
{
padding: 20px;
background-color: #ffffff;
border-radius: 0 4px 4px 4px;
}
a
{
color: #034af3;
}
/* Menu Styles ------------------------------*/
ul#menu
{
padding: 0px;
position: relative;
margin: 0;
}
ul#menu li
{
display: inline;
}
ul#menu li a
{
background-color: #e8eef4;
padding: 10px 20px;
text-decoration: none;
line-height: 2.8em;
/*CSS3 properties*/
border-radius: 4px 4px 0 0;
}
ul#menu li a:hover
{
background-color: #ffffff;
}
/* Forms Styles ------------------------------*/
fieldset
{
padding-left: 12px;
}
fieldset label
{
display: block;
padding: 4px;
}
input[type="text"], input[type="password"]
{
width: 300px;
}
input[type="submit"]
{
padding: 4px;
}
/* Data Styles ------------------------------*/
table.data
{
background-color:#ffffff;
border:1px solid #c3c3c3;
border-collapse:collapse;
width:100%;
}
table.data th
{
background-color:#e8eef4;
border:1px solid #c3c3c3;
padding:3px;
}
table.data td
{
border:1px solid #c3c3c3;
padding:3px;
}


_ViewStart 文件

Shared 文件夾(位於Views 文件夾內)中的_ViewStart 文件包含如下內容:

@{Layout = "~/Views/Shared/_Layout.cshtml";}

這段代碼被自動添加到由應用程序顯示的所有視圖。

如果您刪除了這個文件,則必須向所有視圖中添加這行代碼。

在本教程後面的章節中,您將學到更多關於視圖的知識。