MVC為Html對象建立一個擴充方法,使用自己的控制項就像使用TextBox一樣方便

來源:互聯網
上載者:User

標籤:str   app   dht   ring   按鈕組   csharp   space   button   text   

先看一下我想要的結果:

很容易它就是一個選項按鈕組,當我後台為Html對象(HtmlHelper的一個執行個體,它被定義在System.Web.Mvc名稱空間下的WebViewPage類,即它對於所有MVC頁面都可用)建立好擴充方法後,使用以下語句就可以產生上面的效果:

@Html.CreateGanderRadioButton()
擴充方法的定義:
namespace Web.Helper
{
    public static class ExtendHtml
    {
        public static MvcHtmlString CreateGanderRadioButton(this System.Web.Mvc.HtmlHelper html)
        {
            StringBuilder str = new StringBuilder();
            str.Append("<input type=‘radio‘ value=1 name=‘gander‘>男");
            str.Append("<input type=‘radio‘ value=0 name=‘gander‘>女");
            return MvcHtmlString.Create(str.ToString());
 
        }
    }
}
注意,它所在的類必須是public static的,也就是說,它的擴充方法本身也是public static的。
對於,直接在頁面上使用我們的方法,還是差了一步,那就是,要在web.config裡把Web.Helper名稱
空間加上,頁面上才能訪問的到:
 <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
        <add namespace="Web.Helper" />
 </namespaces>

 

 

 

OK,現在一個Html對象的擴充方法就做好了,趕快去實踐一個吧!

MVC為Html對象建立一個擴充方法,使用自己的控制項就像使用TextBox一樣方便

相關文章

聯繫我們

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