《Pro ASP.NET MVC 3 Framework》學習筆記之二十八【視圖2】


接着上一篇Views的筆記

在視圖里導入命名空間(Importing Namespaces into a View)

Razor視圖通過一套常用的命名空間編譯,這為我們省去了在使用常用類時指定必要的命名空間的麻煩。如果需要使用我們自己定義的類就必須引入命名空間或者是使用類的完整名稱(包含了命名空間),如下所示:

View Code
@{ 
ViewBag.Title = "Index";
}

Here is some data: @DynamicData.Infrastructure.MyUtility.GetUsefulData()

上面的例子使用了MyUtility類,里面有一個GetUsefulData方法。MyUtility.cs如下所示:

View Code
namespace Views.Infrastructure
{
public static class MyUtility
{
public static string GetUsefulData()
{
return "This is some useful data";
}
}
}

上面是使用的完整類名,也可以使用@using引入命名空間,如下所示:

View Code
@using Views.Infrastructure;
@{
ViewBag.Title = "Index";
}
Here is some data:@MyUtility.GetUsefulData()

當視圖被編譯時,我們指定的命名空間會通過using語句導入,這樣我們就可以在視圖里面直接引用類名。

在Web.config里面添加命名空間

上面在視圖里導入命名空間后,我們也只能在當前的視圖里面使用該命名空間下的類,如果我們想只寫一次導入命名空間的using語句並能夠在當前項目里所有的視圖里面使用,可以采取在Web.config里添加的方式,如下所示:

View Code
  <system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="Views.Infrastructure"/><!--自定義的命名空間-->
</namespaces>
</pages>
</system.web.webPages.razor>

注意這里的Web.config是在Views文件夾里面的,不是根目錄下的Web.config。

理解Razor HTML字符串編碼

XSS(跨站點腳本)是攻擊網站的一種方式,Razor會幫助我們將來自@標簽的輸出進行編碼,從而防止XSS攻擊。這也意味着在HTML里面具有特殊意義的符號會被等同的編碼替換。例如"<"會被替換為lt;為了舉例說明,現在將MyUtility進行修改:

View Code
namespace Views.Infrastructure
{
public static class MyUtility
{
public static string GetUsefulData()
{
return "<form>Enter your password:<input type=text><input type=submit value=\"Log In\"/></form>";
}
}
}

上面只是一個簡單的例子,真正的攻擊非常巧妙而且不會改變頁面。可以運行程序顯示如下:


默認情況是會對輸出進行編碼,如果我們不想編碼輸出,可以返回一個MvcHtmlString的實例,如下:

View Code
namespace Views.Infrastructure
{
public static class MyUtility
{
public static MvcHtmlString GetUsefulData()
{
return new MvcHtmlString("<form>Enter your password:<input type=text><input type=submit value=\"Log In\"/></form>");
}
}
}

運行程序可以看到效果。

使用動態類型視圖(Using Dynamically Typed Views)

當創建一個強類型的視圖時,創建的類是從System.Web.Mvc.WebViewPage<T>派生的,T就是視圖模型類的類型。例如:

@model string 
@{ 
    ViewBag.Title = "Index"; 
} 
...
//編譯為如下的類 
public class _Page_Views_Home_Index_cshtml : System.Web.Mvc.WebViewPage<string> {...} 

如果我們沒有指定具體的類型,那就創建了一個動態類型的視圖,也就是T是dynamic類型的。我們仍然能夠傳遞視圖模型對象給View,但卻是被當作動態類型的,這意味着處理該視圖模型對象類似處理ViewBag了,在動態類型視圖里面,同樣能夠調用視圖模型對象的任何成員,只不過要到運行時才會被檢查。使用動態類型的好處是可以傳遞不同的視圖模型類型(View Model Types)到視圖。缺點是如果我們傳遞一個不屬於該對象的成員時,當調用該視圖就會會拋異常,但在編譯的時候是發現不了這個錯誤的。這里不推薦隨便使用動態類型。

使用HTML輔助方法(Using HTML Helpers)

MVC框架里面提供了一序列的HTML輔助方法來幫助我們生成HTML標簽,從而提高我們的開發效率。

創建內嵌的HTML輔助方法

這是最直接的使用方式,如下:

View Code
//HomeController代碼
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string message = "Hello World";
            return View((object)message);
        }

        public ViewResult Calculate()
        {
            ViewBag.X = 10;
            ViewBag.Y = 20;
            return View();
        }

        public ActionResult InlineHelper()
        {
            ViewBag.Days = new[] { "Monday", "Tuesday", "Wednesday", "etc" };
            ViewBag.Fruites = new[] { "Apples", "Mango", "Banana" };
            return View();
        }
    }
//添加對應的視圖,如下
@{
    ViewBag.Title = "InlineHelper";
}
@helper CreateList(string[] items)
    {
    <ul>
        @foreach (string item in items)
        {
            <li>@item</li> 
        }
    </ul>
}
<h4>
    InlineHelper</h4>
Days of week:<p />
@CreateList(ViewBag.Days)
<p />
Fruite I like:<p />
@CreateList(ViewBag.Fruites)

內嵌的helpers有方法名和參數,這類似於通常的C#方法。在上面的例子中,我們定義了一個CreateList的helper。

創建一個擴展的helper方法(Creating an External Helper Method)

內嵌helper方法非常方便,但是只能在當前的視圖里面使用,如果想在其他的視圖里面也使用的話,可以創建一個擴展的HTML helper方法,如下:

View Code
using System.Web.Mvc;

namespace Views.Infrastructure.HtmlHelpers
{
    public static class CustomHtmlHelpers
    {
        public static MvcHtmlString List(this HtmlHelper html, string[] listItems)
        {
            TagBuilder tag = new TagBuilder("ul");
            foreach (string item in listItems)
            {
                TagBuilder itemTag = new TagBuilder("li");
                itemTag.SetInnerText(item);
                tag.InnerHtml += itemTag.ToString();
            }
            return new MvcHtmlString(tag.ToString());
        }
    }
}

第一個參數是擴展的HTML helper方法,是HtmlHelper對象。

在一個Helper方法里面創建HTML標簽的最簡單的方式就是使用TagBuilder類,它讓我們不需要處理特別的字符就能夠很方便的創建HTML。

TagBuilder類是System.Web.WebPages程序集的一部分,但是使用了CLR的一個功能: type forwarding(暫且稱為類型轉遞吧,如果你有更好的解釋,記得留言給我,謝謝),這個功能讓我們能夠將程序集的某一個類型指向其他的程序集,而不用重新編譯就可以在其他的程序集里面使用原來程序集的類型。所以這里也是作為System.Web.Mvc程序集的一部分,因為TagBuilder從System.Web.WebPages通過類型轉遞指向了System.Web.Mvc,這也是為什么這里只需要引用System.Web.Mvc這個命名空間就行了。

下面是關於TagBuilder類的一些屬性:

InnerHtml:設置HTML元素的內容,是不會被編碼的。
SetInnerText(string):設置HTML元素的文本內容,這里的string是被編碼過的。
AddCssClass(string):添加css樣式
MergeAttribute(string,string,bool):添加特性,第一個參數是屬性的名字,第二個是值,bool類型表示是否替換已經存在的同名屬性。

HTML Helper方法的結果是一個MvcHtmlString對象,該對象包含的內容直接寫到了對客戶端的響應流里面,記住:MvcHtmlString的內容是沒有經過編碼就直接傳遞給了Response,這也就意味着我們必須自己編碼可能導致XSS攻擊的數據。這里可以采取TagBuilder.SetInnerText方法,它會對字符串進行編碼,或者是顯示使用HtmlHelper對象的Encode方法進行編碼。

接着在HomeController里面添加一個action方法,並添加對應的視圖,如下:

View Code
//HomeController 
public ActionResult ExternalHelper()
{
      ViewBag.Days = new[] { "Monday", "Tuesday", "Wednesday", "etc" };
      ViewBag.Fruits = new[] { "Apples", "Mango", "Banana" };
      return View();
}

//對應的View
@using Views.Infrastructure.HtmlHelpers;
@{
    ViewBag.Title = "ExternalHelper";
}
<h2>
    ExternalHelper</h2>
Day of the week:<p />
@Html.List((string[])ViewBag.Days)
<p />
Fruite I like:<p />
@Html.List((string[])ViewBag.Fruits)
@Html.List(new string[] { "<form>Enter your password:<input type=text><input type=submit value=\"Log In\"/></form>" })

 

使用內置的HTML Helper方法(Using the Built-in HTML Helpers)

MVC框架包含了一些經過挑選的HTML helper方法,這些方法可以幫助創建HTML片段或執行通常的任務。

創建表單

兩個非常有用的方法就是 Html.BeginForm和Html.EndForm,它們幫助創建表單標簽並生成一個基於路由機制的action的屬性。如:@{Html.BeginForm("Index","Home");} @{Html.EndForm();},這些helper方法需要在Razor代碼塊里面被調用,這會使得代碼看起不雅。一個更加優雅的方式是使用using語句,如:@using (Html.BeginForm("Index", "Home")) {...}

這種方式非常巧妙,因為BeginForm方法創建了一個MvcForm類的實例,這個類實現了IDisposable接口。這意味着當程序跳出using語句塊時,.NET框架會對MvcForm對象調用Dispose方法,並輸出closing Form標簽。BeginForm有很多重載的版本,不同的表單允許我們指定怎樣創建HTML表單元素的action屬性。

創建表單與回發到同一URL:BeginForm默認的重載版本是不帶參數的並生成一個指向當前action的URL,也就是這個action來處理當前的回發請求。這是MVC程序里面常見的模式,Get和Post請求使用同一個URL來處理。Get請求展示HTML表單,Post請求驗證並處理提交過來的數據。如下:

View Code
public class SomeController : Controller
{  
   public ViewResult MyAction() {  
       /* 展示表單*/  
   } 
 
   [HttpPost] 
   public ActionResult MyAction(MyModel incomingData) { 
       /* 處理Post請求 */  
   } 
} 

使用Input Helpers(Using Input Helpers)

當HTML表單里添加了Input元素后,表單才有意義。下面是一些基本的HTML Helpers用來創建Input元素,如下:

View Code
Html.CheckBox("myCheckbox", false) 
輸出:  
<input id="myCheckbox" name="myCheckbox" type="checkbox" value="true" /> 
<input name="myCheckbox" type="hidden" value="false" />
 
Html.Hidden("myHidden", "val") 
輸出:    
<input id="myHidden" name="myHidden" type="hidden" value="val" /> 

Html.RadioButton("myRadiobutton", "val", true) 
輸出: 
<input checked="checked" id="myRadiobutton" name="myRadiobutton" 
type="radio" value="val" /> 

Html.Password("myPassword", "val") 
輸出:  <input id="myPassword" name="myPassword" type="password" value="val" /> 

Html.TextArea("myTextarea", "val", 5, 20, null) 
輸出:  
<textarea cols="20" id="myTextarea" name="myTextarea" rows="5"> val</textarea> 

Html.TextBox("myTextbox", "val") 
輸出: 
<input id="myTextbox" name="myTextbox" type="text" value="val" /> 

注:checkbox方法呈現了兩個input元素,一個是checkbox,一個是hidden元素,它們的name相同。有兩個input元素的原因是瀏覽器不會提交沒有被選中的checkbox的值。使用一個hidden控件確保在這種請求發生時MVC框架也能夠獲取hidden的值。

如果我們想指定一個值,可以使用標准的Razor句法,像這樣:@Html.CheckBox("myCheckBox", Model),一個更加有趣的重載版本是只獲取一個參數,這個參數被用來搜索視圖數據,ViewBag以及視圖模型。舉個例子:如果調用@Html.TextBox("DataValue"),MVC框架視圖尋找跟該鍵值DataValue一致的數據項,搜索的路徑如下:
•  ViewBag.DataValue  •  ViewData["DataValue"] •  @Model.DataValue

第一個被搜到的值被用來設置創建的HTML元素的value屬性值,如果我們指定一個像DataValue.First.Name,那搜索會變得更加復雜,會檢查如下的值是否移植:

View Code
•  ViewBag.DataValue.First.Name 
•  ViewBag.DataValue["First"].Name 
•  ViewBag.DataValue["First.Name"] 
•  ViewBag.DataValue["First"]["Name"] 
•  ViewData["DataValue.First.Name"] 
•  ViewData["DataValue"].First.Name 
•  ViewData["DataValue.First"].Name 

如上所示,有很的排列的,一旦第一個值找到,搜索就會終止。這里我們或許會擔心程序的性能,記住一點通常情況下,只有非常少的項在ViewBag或ViewData里面,所以搜索並不會花費很長時間。input helper方法會自動編碼數據防止XSS。

使用強類型的Input Helper方法(Using Strongly Typed Input Helpers)

針對上面每一個基本input方法都有一個對應的強類型的Helper方法。如下所示:

View Code
Html.CheckBoxFor(x => x.IsApproved) 
輸出: 
<input id="IsApproved" name="IsApproved" type="checkbox" value="true" /> 
<input name="IsApproved" type="hidden" value="false" /> 

Html.HiddenFor(x => x.SomeProperty) 
輸出:<input id="SomeProperty" name="SomeProperty" type="hidden" value="value" /> 

Html.RadioButtonFor(x => x.IsApproved, "val") 
輸出:<input id="IsApproved" name="IsApproved" type="radio" value="val" />  

Html.PasswordFor(x => x.Password) 
輸出:<input id="Password" name="Password" type="password" /> 

Html.TextAreaFor(x => x.Bio, 5, 20, new{}) 
輸出:<textarea cols="20" id="Bio" name="Bio" rows="5"> 
Bio value</textarea> 

Html.TextBoxFor(x => x.Name) 
輸出:<input id="Name" name="Name" type="text" value="Name value" /> 

這里會用到Lambda表達式,傳遞給表達式的值是視圖模型對象,並且能夠查詢到用來設置value值的字段或屬性。
添加Attributes到HTML:大多數helper方法具有一個讓我們可以添加任意的屬性到以創建的HTML元素,我們可以使用動態類型來表述屬性及其關聯的值,像這樣:
@Html.TextBox("MyTextBox", "MyValue",new { @class = "my-ccs-class", mycustomattribute = "my-value" })

創建Select元素(Creating Select Elements)

下面展示了可以用來創建Select元素的HTML helper方法:

View Code
Html.DropDownList("myList", new SelectList(new [] {"A", "B"}), "Choose") 
輸出: 
<select id="myList" name="myList"> 
<option value="">Choose</option> 
<option>A</option> 
<option>B</option> 
</select> 

Html.DropDownListFor(x => x.Gender, new SelectList(new [] {"M", "F"})) 
輸出:  
<select id="Gender" name="Gender"> 
<option>M</option> 
<option>F</option> 
</select> 

Html.ListBox("myList", new MultiSelectList(new [] {"A", "B"})) 
輸出: 
<select id="myList" multiple="multiple" name="myList"> 
<option>A</option> 
<option>B</option> 
</select> 

Html.ListBoxFor(x => x.Vals, new MultiSelectList(new [] {"A", "B"})) 
輸出: 
<select id="Vals" multiple="multiple" name="Vals"> 
<option>A</option> 
<option>B</option> 
</select>

Select helper方法獲取SelectList或MultiSelectList參數,這兩個參數不同的是MultiSelectList具有讓我們能夠指定一個或多個被選中項的構造器。這兩個類都是操作對象的枚舉序列。假設有這樣一個類Region:public class Region{public int RegionID{get;set;} public string RegionName{get;set;}},action方法在視圖放置了一個SelectList對象,如下:

View Code
List<Region> regionsData = new List<Region> { 
    new Region { RegionID = 7, RegionName = "Northern" }, 
    new Region { RegionID = 3, RegionName = "Central" }, 
    new Region { RegionID = 5, RegionName = "Southern" }, 
}; 
ViewData["region"] = new SelectList(regionsData,  // 數據項
                                       "RegionID",   // 值字段 
                                       "RegionName", // 文本字段 
                                       3);           // 選中值 
這里的 <%: Html.DropDownList("region", "Choose")  %> 將呈現如下HTML:  
<select id="region" name="region"> 
<option value="">Choose</option> 
<option value="7">Northern</option> 
<option selected="selected" value="3">Central</option> 
<option value="5">Southern</option> 
</select> 

正如我們所看到的,RegionID和RegionName的屬性值使用在select元素包含的option的inner文本和value值。

創建鏈接和URL(Creating Links and URL)

這里介紹的HTML helper方法讓我們使用路由系統的輸出URL生成功能(前面的章節有介紹)呈現HTML鏈接和原始的URL。這些helper方法的輸出依賴於我們程序的路由配置。
下面是一些有關的方法展示:

View Code
Url.Content("~/my/content.pdf") 
輸出:  /my/content.pdf 

Html.ActionLink("Hi", "About", "Home") 
輸出:  <a href="/Home/About">Hi</a>  

Html.ActionLink("Hi", "About", "Home", "https","www.example.com", "anchor", new{}, null) 
輸出:  <a href="https://www.example.com/Home/About#anchor">Hi</a>  

Url.Action("About", "Home") 
輸出:  /Home/About 

Url.RouteUrl(new { controller = "c", action = "a" }) 
輸出:  /c/a 
                                                  
Html.RouteLink("Hi", new { controller = "c", action = "a" }, null) 
輸出:  <a href="/c/a">Hi</a> 

Html.RouteLink("Hi", "myNamedRoute", new {}) 
輸出:  <a href="/url/for/named/route">Hi</a> 

使用WebGrid Helper(Using the WebGrid Helper)

該方法生成以網格形式展示數據項的HTML元素,使用了HTML table元素。下面通過示例說明:
在HomeController里面添加一個action Grid如下:

View Code
        public ActionResult Grid()
        {
            IEnumerable<Product> productList = new List<Product> {
                            new Product {Name = "Kayak", Category = "Watersports", Price = 275m},
                new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95m},
                new Product {Name = "Soccer ball", Category = "Football", Price = 19.50m},
                new Product {Name = "Corner flags", Category = "Football", Price = 34.95m},
                new Product {Name = "Stadium", Category = "Football", Price = 79500m},
                new Product {Name = "Thinking cap", Category = "Chess", Price = 16m}
            };

            ViewBag.WebGrid = new WebGrid(source: productList, rowsPerPage: 4);
            return View(productList);
        }

對應的視圖代碼如下:

View Code
@model IEnumerable<Views.Models.Product>
@{
    var grid = new WebGrid(source: Model, rowsPerPage: 4);
}
@grid.GetHtml(tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns(
grid.Column("Name", "Item", style: "textCol"),
grid.Column("Price", style: "numberCol",
format: @<text>$@string.Format("{0:F2}", item.Price)</text>)
))

我們在兩個部分使用WebGrid helper方法,第一個部分包含在Razor代碼塊里面並且定義WebGrid對象。設置source參數值為視圖模型(Product對象),這些是展示在grid里的項。我們將定義和使用grid分為兩個步驟,定義里面另一個參數提供了rowPerPage,WebGrid支持分頁。

有非常多的構造器參數來讓我們指定grid的生成行為,下面是一些參數的描述:

Source:數據源(默認為null)   columnNames:定義被用作列數據源的項(默認為null)   rowsPerPage:指定每頁多少行(默認為10)   canPage:啟用/禁用分頁(默認true)  
canSort:啟用/禁用排序(默認true)

第二個部分使用WebGrid helper方法生成HTML,這里是通過調用GetHtml方法實現。傳遞給這個方法參數讓我們可以控制HTML的呈現。
WebGrid.GetHtml方法的參數列表如下:


列的參數給我們提供一種配置個性化列的方式。運行下程序可以試試效果,很明顯能夠知道每點擊一次header列,會重新加載所有數據,如果需要考慮性能這里可以使用緩存。
如果我們不喜歡在視圖里面定義WebGrid helper方法,感覺這應該是在action方法里面完成的,感覺沒錯,我們可以在action里面定義,如:

View Code
//action方法
public ActionResult Grid() { IEnumerable<Product> productList = new List<Product> { new Product {Name = "Kayak", Category = "Watersports", Price = 275m}, new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95m}, new Product {Name = "Soccer ball", Category = "Football", Price = 19.50m}, new Product {Name = "Corner flags", Category = "Football", Price = 34.95m}, new Product {Name = "Stadium", Category = "Football", Price = 79500m}, new Product {Name = "Thinking cap", Category = "Chess", Price = 16m} }; ViewBag.WebGrid = new WebGrid(source: productList, rowsPerPage: 4); return View(productList); } //視圖只需要將第一部分換成如下所示:
@model IEnumerable<DynamicData.Models.Product> @{ var grid = (WebGrid)ViewBag.WebGrid;} @grid.GetHtml( tableStyle: "grid", headerStyle: "header", rowStyle: "row", footerStyle: "footer", alternatingRowStyle: "altRow", columns: grid.Columns ( grid.Column("Name", "Item", style:"textCol"), grid.Column("Price", style: "numberCol", format: @<text>$@string.Format("{0:F2}", item.Price) </text>) )) 

 

使用圖表helper方法(Using the Chart Helper)

MVC里面的Chart Helper提供非常多的功能來展示圖表,這里僅僅是簡要介紹,詳詢MSDN的相關內容。添加一個action方法,如下:

View Code
        public void Chart()
        {
            IEnumerable<Product> productList = new List<Product> { 
                            new Product {Name = "Kayak", Category = "Watersports", Price = 275m},
                new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95m},
                new Product {Name = "Soccer ball", Category = "Football", Price = 19.50m},
                new Product {Name = "Corner flags", Category = "Football", Price = 34.95m},
                new Product {Name = "Stadium", Category = "Football", Price = 150m},
                new Product {Name = "Thinking cap", Category = "Chess", Price = 16m}
            };
            Chart chart = new Chart(400, 200, @"<Chart BackColor=""Gray"" BackSecondaryColor=""WhiteSmoke""  
                        BackGradientStyle=""DiagonalRight"" AntiAliasing=""All"" 
                        BorderlineDashStyle = ""Solid"" BorderlineColor = ""Gray"">
                        <BorderSkin SkinStyle = ""Emboss"" />
                        <ChartAreas>
                            <ChartArea Name=""Default"" _Template_=""All"" BackColor=""Wheat"" 
                                BackSecondaryColor=""White"" BorderColor=""64, 64, 64, 64"" 
                                BorderDashStyle=""Solid"" ShadowColor=""Transparent"">
                        </ChartArea>
                    </ChartAreas>
                </Chart>");

            chart.AddSeries(chartType: "Column", yValues: productList.Select(e => e.Price).ToArray(),
                xValue: productList.Select(e => e.Name).ToArray());
            chart.Write();
        }

里面一個非常重要的方法是Chart.Write,它會將生成的圖表作為圖片直接響應輸出。,最簡單的在web頁面里面包含圖表的方式就是使用部分視圖。
還有一些其他的內置Helper方法如下:
Crypto(提供常用的加密散列功能)  WebMail(通過SMTP發郵件)  Json(處理Json數據)  ServerInfo(獲取關於服務器的信息) WebImage(加載及簡單的處理圖片)

使用片段(Using Sections)

Razor引擎支持的分片的概念,讓我們能夠在一個布局里面提供內容區域。Razor分片功能能夠更好的控制在視圖的那部分插入布局以及在放置在哪個位置。如下:

View Code
//SectionIndex視圖代碼
@{
    ViewBag.Title = "SectionIndex";
}
@section Header{
    @foreach (string str in new[] { "Home", "List", "Edit" })
    {
        <div style="float: left; padding: 5px;">
            @Html.ActionLink(str, str)
        </div>
    }
    <div style="clear: both">
    </div>
}
@section Body{
    <h4>
        This is the body section</h4>
}
@section Footer{
    <h4>
        This is the footer</h4>
}

//_Layout.cshtml代碼
<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>

<body>

    @RenderSection("Header")

    <h4>This is the layout between the header and the body</h4>

    @RenderSection("Body")

    <h4>This is the layout between the body and the footer</h4>

    @RenderSection("Footer")

    @*@RenderBody()*@

</body>
</html>

@RenderSection("Footer",false)這個重載版本表示Footer Section是可選的,當我們定義了Footer Section時則顯示出來,如果沒有定義也不會拋異常。

使用部分視圖和強類型的部分視圖

通過示例下說明:

View Code
//在Views/Shared下創建一個部分視圖
@{
    Layout = null;
}

<p>This is my partial view</p>
//創建PartialDemo視圖如下
@{
    ViewBag.Title = "PartialDemo";
}
<p>This is the method rendered by the action method</p>
@Html.Partial("MyPartial")
//@Html.Partial("MyStronglyTypedPartial", new [] {"Apples", //"Mangoes", "Oranges"}) 

//在Shared下創建一個強類型的部分視圖
@model IEnumerable<string> 
 
<p>This is my strongly-typed partial view</p> 
<ul> 
@foreach (string val in Model) { 
<li>@val</li> 
} 
</ul> 

注:Razor視圖引擎用同樣的方式尋找部分視圖,這意味着我們可以指定了控制器的部分視圖並且可以重載在Shared文件夾下的同名部分視圖,這可能有點怪,但是一種最常用的部分視圖使用方式就是在layout里面呈現內容。

使用子Action(Using Child Actions)

Child actions是在一個視圖內被調用的Action方法,這可以讓我們在多個頁面重用控制器邏輯並包含與正在運行的主要action不相關的數據。我在SportsStore項目使用過這個技術,當時用作每個頁面的導航菜單。
創建一個Child action如下:

View Code
[ChildActionOnly]
public ActionResult Time(DateTime time)
{
     return View(time);
}
//添加對應的視圖
@model DateTime
@{
    Layout = null;
}
<p>
    The time is: @Model.ToShortTimeString()</p>
//在視圖里面使用Child Action
@{
    ViewBag.Title = "Child Action Demonstration";
}
<p>
    This is the method rendered by the action method</p>
@Html.Action("Time", new { time = DateTime.Now })
<p>
    This is the method rendered by the action method again</p>

好了,關於是視圖的筆記到這里就做完了,后面是關於Model的內容。
晚安!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM