ASP.NET MVC 4 (六) 協助函數

來源:互聯網
上載者:User

標籤:

協助函數封裝一些代碼,方便我們在應用程式中重用,MVC內建很多協助函數,可以很方便的產生HTML標記。首先列出後面樣本中用到的資料模型類定義:

namespace HelperMethods.Models {    public partial class Person {        public int PersonId { get; set; }        public string FirstName { get; set; }        public string LastName { get; set; }        public DateTime BirthDate { get; set; }        public Address HomeAddress { get; set; }        public bool IsApproved { get; set; }        public Role Role { get; set; }    }    public class Address {        public string Line1 { get; set; }        public string Line2 { get; set; }        public string City { get; set; }        [Display(Name = "ZIP CODE")]        public string PostalCode { get; set; }        public string Country { get; set; }    }    public enum Role {        Admin,        User,        Guest    }}

控制器的定義:

namespace HelperMethods.Controllers {    public class HomeController : Controller {        public ActionResult Index() {            ViewBag.Fruits = new string[] { "Apple", "Orange", "Pear" };            ViewBag.Cities = new string[] { "New York", "London", "Paris" };            string message = "This is an HTML element: <input>";            return View((object)message);        }        public ActionResult CreatePerson() {            return View(new Person { Role = Role.Guest});        }        [HttpPost]        public ActionResult CreatePerson(Person person) {            return View("DisplayPerson", person);        }    }}

 

內聯協助函數

我們可以直接在視圖中定義內聯的協助函數,使用@helper標記內嵌函式定義:

@model string@{    Layout = null;}@helper ListArrayItems(string[] items){    foreach (string str in items)    {        <b>@str </b>    }}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>Index</title></head><body>    <div>        Here are the fruits: @ListArrayItems(ViewBag.Fruits)    </div>    <div>        Here are the cities: @ListArrayItems(ViewBag.Cities)    </div>    <div>        Here is the message:        <p>@Model</p>    </div></body></html> 

這裡定義了一個內聯協助函數ListArrayItems,後續我們可以重用它顯示數值內容,內聯協助函數沒有傳回值。在調用ListArrayItems時我們也沒有對參數做類型Cast,MVC會自動實作類別型轉換。

外部協助函數

內聯協助函數雖然很方便,但是只能在視圖中定義和使用,如果內嵌函式很複雜會讓視圖很難讀得清楚,對此我們可以定義外部協助函數,外部協助函數實際上是對HtmlHelper類的方法擴充,上面的內聯協助函數改寫成外部協助函數是這樣的:

namespace HelperMethods.Infrastructure {    public static class CustomHelpers {        public static MvcHtmlString ListArrayItems(this HtmlHelper html, string[] list) {            TagBuilder tag = new TagBuilder("ul");            foreach(string str in list) {                TagBuilder itemTag = new TagBuilder("li");                itemTag.SetInnerText(str);                tag.InnerHtml += itemTag.ToString();            }            return new MvcHtmlString(tag.ToString());        }    }}

HtmlHelper暴露一些屬性比如RouteCollection、ViewBag、ViewContext方便我們擷取當前請求相關的資料。外部協助函數最後返回一個MvcHtmlString對象,它的內容直接寫到輸出響應。我們可以這樣在視圖中使用自訂的外部協助函數:

@model string@using HelperMethods.Infrastructure@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>Index</title></head><body>    <div>        Here are the fruits: @Html.ListArrayItems((string[])ViewBag.Fruits)    </div>    <div>        Here are the cities: @Html.ListArrayItems((string[])ViewBag.Cities)    </div>    <div>        Here is the message:        <p>@Model</p>    </div></body></html> 

我們需要引入定義外部協助函數的命名空間,也可以定義在/Views/Web.config中供所有的視圖使用。使用@html來調用外部協助函數,它返回一個HtmlHelper類的執行個體,在調用外部協助函數時也要做參數類型轉化。

協助函數中的字串編碼

在使用協助函數時我們需要注意HTML編碼的問題,先來看看下面一個問題,如果我們在控制器action中輸出一些帶HTML標記的字串到視圖:

public ActionResult Index() {   string message = "This is an HTML element: <input>";   return View((object)message); } 

在視圖中直接輸出這個字串:

@model string@{    Layout = null;}<!DOCTYPE html><html><head>    <title>Index</title></head><body>    <p>This is the content from the view:</p>    <div>        Here is the message:        <p>@Model</p>    </div></body></html>

最後Razor輸出的結果是:

... <div> Here is the message: <p>This is an HTML element: &lt;input&gt;</p> </div> ... 

<input>中的“<>”標籤被編碼為相應的字元而非HTML標籤,這是出於安全的考慮,防止動態嵌入HTML標記甚至Javascript指令碼。如果是從協助函數中輸出HTML標籤又是怎樣的結果呢?看下面的例子:

public static MvcHtmlString DisplayMessage(this HtmlHelper html, string msg) {     string result = String.Format("This is the message: <p>{0}</p>", msg);   return new MvcHtmlString(result); }

視圖檔案中調用這個協助函數輸出HTML標記:

<p>This is the content from the helper method:</p> <div style="border: thin solid black; padding: 10px"> @Html.DisplayMessage("This is an HTML element: <input>") </div> 

這次得到的就是HTML的<input>編輯框,這是因為我們的HTML協助函數返回的MvcHtmlString被信任為安全的,對輸出的結果不再做HTML編碼。如果協助函數返回的不是MvcHtmlString,只是普通的String,比如:

public staticstring DisplayMessage(this HtmlHelper html, string msg) {   return String.Format("This is the message: <p>{0}</p>","This is an HTML element: <input>"); } 

這時候字串又會被HTML編碼,不會輸出input標籤。但這樣的結果是<p>標記也會被HTML編碼,這不是我們想要的結果,正確的做法是:

public static MvcHtmlStringDisplayMessage(this HtmlHelper html) {   string encodedMessage = html.Encode("This is an HTML element: <input>");   string result = String.Format("This is the message: <p>{0}</p>", encodedMessage);   return new MvcHtmlString(result); } 

我們使用html.Encode()對動態內容編碼,結果仍然返回MvcHtmlString對象,這樣就避免了動態內容嵌入帶來的安全性漏洞,也使真正要顯示的HTML標記被正確的渲染。

內建的Form協助函數

我們可以直接使用HTML的Form標記建立一個表單來編輯要提交的資料:

@model HelperMethods.Models.Person@{    ViewBag.Title = "CreatePerson";}<h2>CreatePerson</h2><form action="/Home/CreatePerson" method="post">    <div class="dataElem">        <label>PersonId</label>        <input name="personId" value="@Model.PersonId" />    </div>    <div class="dataElem">        <label>First Name</label>        <input name="FirstName" value="@Model.FirstName" />    </div>    <div class="dataElem">        <label>Last Name</label>        <input name="lastName" value="@Model.LastName" />    </div>    <input type="submit" value="Submit" /></form> 

這樣的問題是必須寫入程式碼表單提交的URL,實際上我們可以使用內建的BeginForm協助函數建立一個表單:

@Html.BeginForm()<div class="dataElem">    <label>PersonId</label>    <input name="personId" value="@Model.PersonId" /></div><div class="dataElem">    <label>First Name</label>    <input name="FirstName" value="@Model.FirstName" /></div><div class="dataElem">    <label>Last Name</label>    <input name="lastName" value="@Model.LastName" /></div><input type="submit" value="Submit" />@{Html.EndForm();} 

BeginForm開始一個表單,EndForm結束表單,實際上更常用的寫法是是使用Razor代碼塊: 

@using (Html.BeginForm()){    <div class="dataElem">        <label>PersonId</label>        <input name="personId" value="@Model.PersonId" />    </div>    <div class="dataElem">        <label>First Name</label>        <input name="FirstName" value="@Model.FirstName" />    </div>    <div class="dataElem">        <label>Last Name</label>        <input name="lastName" value="@Model.LastName" />    </div>    <input type="submit" value="Submit" />} 

@using建立一個自閉合的表單,不再需要調用EndForm。不帶參數的BeginForm將表單提交到當前控制器的當前action方法,除此之外BeginForm還有很多重載形式,下面給出一些使用的例子:

@using (Html.BeginForm("CreatePerson", "Home",new { id = "MyIdValue" }, FormMethod.Post,new { @class = "personClass", data_formType="person"})) { ...}

這裡CreatePerson指定了表單要提交到的控制器,Home為要提交到的action,new { id = "MyIdValue" }為額外的路徑映射參數,FormMethod.Post指定使用HTTP post方法提交資料,new { @class = "personClass", data_formType="person"}指定Form標記的屬性,得到的表單HTML結果是這樣的:

... <form action="/Home/CreatePerson/MyIdValue" class="personClass" data-formType="person" method="post"> ... 

我們還可以指定表單使用的路徑映射產生提交到的連結,比如我們註冊了這樣一條路徑映射:

routes.MapRoute( name: "FormRoute", url: "app/forms/{controller}/{action}" ); 

我們使用BeginRouteForm建立表單並指定要使用的路徑映射記錄:

@using(Html.BeginRouteForm("FormRoute", new {}, FormMethod.Post, new { @class = "personClass", data_formType="person"})) { ...}

最後得到的結果是:

... <form action="/app/forms/Home/CreatePerson"class="personClass" data-formType="person" method="post"> ... 
內建輸入協助函數

實際上不需要使用諸如<input>的HTML標記來建立資料的編輯框,MVC內建提供了大量的輸入協助函數:

HTML元素 樣本 輸出結果
Checkbox Html.CheckBox("myCheckbox", false)

<input id="myCheckbox" name="myCheckbox" type="checkbox" value="true" /> 
<input name="myCheckbox" type="hidden" value="false" />

Hidden Html.Hidden("myHidden", "val") <input id="myHidden" name="myHidden" type="hidden" value="val" /> 
Radio Html.RadioButton("myRadiobutton", "val", true) 

<input checked="checked" id="myRadiobutton" name="myRadiobutton" 
type="radio" value="val" />

Password Html.Password("myPassword", "val") Html.Password("myPassword", "val")
Text area

Html.TextArea("myTextarea", "val", 5, 20, null)

<textarea cols="20" id="myTextarea" name="myTextarea" rows="5"> 
val</textarea>

Text box  Html.TextBox("myTextbox", "val") <input id="myTextbox" name="myTextbox" type="text" value="val" /> 

 

每一種輸入標記函數都有多種重載形式,可以提供額外的參數指定標籤的特性。需要注意的是CheckBox,它會產生兩條input標記,其中一個類型為hidden,這是因為瀏覽器在checkbox未選中時不會提交資料,這條hidden的標記使得MVC即使未在複選框未選中時也能獲得相應的資料。

使用輸入協助函數前面的表單可以這樣寫:

@model HelperMethods.Models.Person@{    ViewBag.Title = "CreatePerson";}<h2>CreatePerson</h2>@using (Html.BeginRouteForm("FormRoute", new { }, FormMethod.Post,new { @class = "personClass", data_formType = "person" })){    <div class="dataElem">        <label>PersonId</label>        @Html.TextBox("personId", @Model.PersonId)    </div>    <div class="dataElem">        <label>First Name</label>        @Html.TextBox("firstName", @Model.FirstName)    </div>    <div class="dataElem">        <label>Last Name</label>        @Html.TextBox("lastName", @Model.LastName)    </div>    <input type="submit" value="Submit" />} 

我們為每個輸入欄位指定了名稱,如果指定的名稱和視圖模型的某個屬性名稱不一致,MVC將不能成功的綁定和建立模型對象,我們可以使用這種替代的方式:

 

我們不需要再給出欄位值,MVC自動根據傳入的字串從View data、viewbag及view model中尋找對應的值,比如調用@Html.TextBox("DataValue"),MVC視圖從ViewBag.DataValue、@Model.DataValue擷取數值,使用第一個找到的結果。更複雜點的@Html.TextBox("DataValue.First.Name"),MVC搜尋路徑也更多:

•  ViewBag.DataValue.First.Name•  ViewBag.DataValue["First"].Name•  ViewBag.DataValue["First.Name"]•  ViewBag.DataValue["First"]["Name"]

同樣,在找到第一個可用值後搜尋停止,這勢必造成效能上的一些損失,但是使得我們建立編輯表單更為簡單。

強型別輸入協助函數

上節中每一種基本輸入協助函數都有對應的強型別形式,強型別輸入協助函數只能用在強型別視圖中。

HTML元素 樣本 輸出結果
Checkbox Html.CheckBoxFor(x => x.IsApproved)

<input id="IsApproved" name="IsApproved" type="checkbox" value="true" /> 
<input name="IsApproved" type="hidden" value="false" />

Hidden Html.HiddenFor(x => x.FirstName) <input id="FirstName" name="FirstName" type="hidden" value="" />
Radio Html.RadioButtonFor(x => x.IsApproved, "val") input id="IsApproved" name="IsApproved" type="radio" value="val" />
Password Html.PasswordFor(x => x.Password)  <input id="Password" name="Password" type="password" /> 
Text area  Html.TextAreaFor(x => x.Bio, 5, 20, new{}) <textarea cols="20" id="Bio" name="Bio" rows="5">Bio value</textarea>
Text box Html.TextBoxFor(x => x.FirstName)  <input id="FirstName" name="FirstName" type="text" value="" />

強型別輸入協助函數使用Lambda運算式從視圖模型中抽取欄位或者屬性,所產生的HTML結果和基本輸入沒有什麼不同,只是協助我們編程時減少輸入的錯誤。上面的例子使用強型別輸入函數是這樣的:

@model HelperMethods.Models.Person@{    ViewBag.Title = "CreatePerson";}<h2>CreatePerson</h2>@using (Html.BeginRouteForm("FormRoute", new { }, FormMethod.Post,new { @class = "personClass", data_formType = "person" })){    <div class="dataElem">        <label>PersonId</label>        @Html.TextBoxFor(m => m.PersonId)    </div>    <div class="dataElem">        <label>First Name</label>        @Html.TextBoxFor(m => m.FirstName)    </div>    <div class="dataElem">        <label>Last Name</label>        @Html.TextBoxFor(m => m.LastName)    </div>    <input type="submit" value="Submit" />} 
選擇元素協助函數

MVC提供以下協助函數用以產生HTML的select元素: 

HTML元素 樣本 輸出結果
Drop-down list  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>

Multiple-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協助函數使用SelectList或者MultilSelectList參數,兩者的區別在於後者建立的允許多選的select。Select協助函數所用的數值為IEnumerbale類型,比如我們要建立一個枚舉類型的選擇編輯框:

<div class="dataElem"> <label>Role</label> @Html.DropDownListFor(m => m.Role, new SelectList(Enum.GetNames(typeof(HelperMethods.Models.Role)))) </div>

HelperMethods.Models.Role是一個C#的枚舉類型,輸出的結果是:

<div class="dataElem">   <label>Role</label>   <select data-val="true" data-val-required="The Role field is required."  id="Role" name="Role">     <option selected="selected">Admin</option>     <option>User</option>     <option>Guest</option>   </select> </div> 

data-val和data-val-required兩個特性是和資料驗證相關的,後文中再來詳細分析。

 

以上為對《Apress Pro ASP.NET MVC 4》第四版相關內容的總結,不詳之處參見原版 http://www.apress.com/9781430242369。  

ASP.NET MVC 4 (六) 協助函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.