1. 程式人生 > >Asp.net Mvc Framework 八 (Helper)

Asp.net Mvc Framework 八 (Helper)

本人已經瘋了...快寫完了而關掉瀏覽器丟失資料之事在此文章上發生了兩次,所以本人倍加珍惜

這節講 一下Asp.netMVC中的Helper
何謂Helper,其實就是在View中為了實現一些靈活功能而寫的方法組

其實Asp.net MVC的View是Aspx的頁面,本身可以宣告定義方法,那為什麼要有Helper呢
其實無非是將介面與邏輯分離,而且Asp.net MVC也並不只支援Aspx一種View,在擴充套件包中,也有Castle的NVelocity引擎和Boo所以,如果在Aspx中定義方法的話會影響其擴充套件性和可移植性.而且程式碼也不太好看.

UrlHelper的Action方法 用於生成一個超級連結,它的過載為
        public string Action(string actionName);
        public string Action(string actionName, object values);
        public string Action(string actionName, RouteValueDictionary valuesDictionary);
        public string Action(string actionName, string controllerName);
        public string Action(string actionName, string controllerName, object values);
        public string Action(string actionName, string controllerName, RouteValueDictionary valuesDictionary);

例如我在View中寫Url.Action("Index","Home"),執行後則會生成/Home/Index這個地址
如果你的系統中的URL Routing規則總是變化的話這個Helper則是你必備之選.
publicstring Encode(string url); 這也是UrlHelper的一個方法 使用方法 如<%=Url.Encode("中文")%>功能與Server.UrlEncode相同,這裡不多說了
如果你有特殊需要可以用3.0新特性,擴充套件方法來為UrlHelper來增加新的功能

HtmlHelper則是另一個常用之Helper

它是來生成HTML程式碼用的
eg.
<%=Html.ActionLink("首頁","index","Home")%> 則生成<a href="/Home/Index">首頁</a>
過載方法有:
publicstring ActionLink(string linkText, string actionName);
publicstring ActionLink(string linkText, string actionName, object values);
publicstring ActionLink(string linkText, string actionName, RouteValueDictionary valuesDictionary);
publicstring ActionLink(string linkText, string actionName, string controllerName);
publicstring ActionLink(string linkText, string actionName, string controllerName, object values);        publicstring ActionLink(string linkText, string actionName, string controllerName, RouteValueDictionary valuesDictionary);
當然HTMLHelper的種類就比UrlHelper多得多了
比如有Button
<%=Html.Button("name","value","onclick"%>
生成
<button onclick="onclick" name="name" id="name">value</button>
CheckBox:
<%=Html.CheckBox("name","text"%> 生成
<input value="text" name="name" type="checkbox">&nbsp;text
Form:
<%=Html.Form("Home","Index",FormMethod.Post) %> 生成
<form action="/Home" method="post">System.Web.Mvc.SimpleForm

</form>

當然還有類似於SubmitButton,Image這些方法,這裡就不多講了

注意一點Preview2中Html.Mailto方法有些Bug請儘量避免使用這個方法

吾生也有涯,而知也無涯,以有涯隨無涯,殆己

附:
功能介紹還有幾篇就寫完了,爭求意見,下面可以講示例也可以講對Asp.net MVC進行擴充套件,不知道大家想看什麼,有興趣的朋友可以回覆一下,我做個參考

Asp.net Mvc Framework 系列