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


幫助函數封裝一些代碼,方便我們在應用程序中重用,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  


免責聲明!

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



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