Asp.net Mvc Framework 八 (Helper)

來源:互聯網
上載者:User
本人已經瘋了...快寫完了而關掉瀏覽器遺失資料之事在此文章上發生了兩次,所以本人倍加珍惜

這節講 一下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則是你必備之選.    public string Encode(string url);

這也是UrlHelper的一個方法 使用方法 如<%=Url.Encode("中文")%>功能與Server.UrlEncode相同,這裡不多說了
如果你有特殊需要可以用3.0新特性,擴充方法來為UrlHelper來增加新的功能

HtmlHelper則是另一個常用之Helper
它是來產生HTML代碼用的
eg.<%=Html.ActionLink("首頁","index","Home")%>

則產生<a href="/Home/Index">首頁</a>
重載方法有:public string ActionLink(string linkText, string actionName);
public string ActionLink(string linkText, string actionName, object values);
public string ActionLink(string linkText, string actionName, RouteValueDictionary valuesDictionary);
public string ActionLink(string linkText, string actionName, string controllerName);
public string ActionLink(string linkText, string actionName, string controllerName, object values);        public string 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 系列

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.