Using HTML helper classes to extend HTML controls in MVC

Source: Internet
Author: User
Tags tagname actionlink

Article excerpt from: http://www.cnblogs.com/zhangziqiu/archive/2009/03/18/1415005.html

In the view page, MVC often requires a lot of packaged HTML controls, and this article focuses on how to extend and customize the controls that you need.

----------------------------------------------------------

The HTML helper class is a class that is provided in the ASP. NET MVC framework to generate HTML control code. Essentially, just like in the first way, we can use the HTML helper class to help us generate HTML control code instead of having to manually write HTML code.

At the same time, we can also use extension methods to add custom build controls to the HTML helper class.

Most of the methods of the HTML helper class return the complete string of an HTML control, so you can output the string in the form of <% =html.actionlink ()%> directly where you need to call it.

(1) HtmlHelper classes in ASP.

HTML attributes are provided in ViewPage, which is an instance of the HtmlHelper class. The ASP. NET MVC framework comes with the following methods:

  • Html.ActionLink ()
  • Html.BeginForm ()
  • Html.checkbox ()
  • Html.dropdownlist ()
  • Html.endform ()
  • Html.hidden ()
  • Html.listbox ()
  • Html.password ()
  • Html.radiobutton ()
  • Html.textarea ()
  • Html.textbox ()

    The methods of the commonly used HtmlHelper classes listed above are not a complete list.

    The following example shows how to use the HtmlHelper class:

    <div>        <% using (Html.BeginForm ())           {%>           <label style= "Width:60px;display:inline-block;" > Username:</label>           <% =html.textbox ("UserName", "Ziqiu.zhang", new {style= "width:200px;"}) %>           <br/><br/>            <label style= "Width:60px;display:inline-block;" > Password:</label>           <% =html.password ("Psssword", "123456", new {style = "width:200px;"}) %>                             <%}%>    </div>

    The above code uses Html.BeginForm to output a form object and adds two input to the form object, one using the Html.textbox output, the other using the Html.password output, The difference is that the type of the input control Html.password output is password.

    (2) Extending HTML helper Classes

    We can extend the HtmlHelper class ourselves, adding new extension methods for the HtmlHelper class, thus enabling more functionality.

    Create the Extensions folder in the project where the SpanExtensions.cs file is created. The source code is as follows:

    Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace system.web.mvc{public    Static class Spanextensions    {public        static string Span (this HtmlHelper helper, String ID, string text)        {            return String.Format (@ "<span id=" "{0}" ">{1}</span>", id, text);        }    }

    The above code we have added a span () method for the HtmlHelper class to return the full HTML string for a span.

    Because the namespace is SYSTEM.WEB.MVC, the page does not need to be modified when it is used, and Visual studio automatically recognizes it:

    Please be aware of the namespace, if you do not use the SYSTEM.WEB.MVC namespace, be sure to reference the namespace of your extension method on the page, or our extension method will not be recognized.

    Next you can use our extension method on the page:

    <div>        <!--Use the custom Span method to extend Html Helper-        -<% =html.span ("Textspan", " Extend the HtmlHelper class-generated span by using a custom span method%>    </div>
    (3) using the Tagbuilder class to create an extension method

    The above custom span () method is very simple, but sometimes we have to construct HTML elements with complex structures, and it's awkward to use string concatenation.

    The ASP. NET MVC Framework provides a class that helps us construct HTML elements: Tagbuilder

    The Tagbuilder class has the following methods to help us build HTML control strings:

    Method name Use
    addCssClass () Add Class= "" Property
    Generateid () Add ID that will "." In the ID name Replace with the character of the Idattributedotreplacement property value. Replace by default with "_"
    Mergeattribute () Add a property that has several overloaded methods.
    Setinnertext () Sets the label content, which is the same as setting the innerHTML property if no more tags are nested in the label.
    ToString () The output HTML tag string, with an overload of a parameter, can set the output form of the label to the following enumeration value:
    • Tagrendermode.normal--with start and end tags
    • Tagrendermode.starttag--only the start tag
    • Tagrendermode.endtag--Only the end tag
    • Tagrendermode.selfclosing--single-label form, such as <br/>

    A tagbuilder also has the following key attributes:

    Property name Use
    Attributes All properties of Tag
    Idattributedotreplacement Replace "." When adding an ID. The target character
    InnerHTML Internal HTML content of tag
    TagName HTML tag name, Tagbuilder only the constructor with one parameter-tagname. So tagname is a required attribute

    The following adds a custom HtmlHelper class extension method, which also outputs a <Span> tag:
    public static string Span (this HtmlHelper helper, string ID, string text, string css, Object htmlattributes)        {            //gen The Tagbuilder            var builder = new Tagbuilder ("span") of a certain tag;            Create the ID, and note that you must first set the Idattributedotreplacement property before you execute the Generateid method.            Builder. Idattributedotreplacement = "-";            Builder. Generateid (ID);                        Add Property                        Builder. Mergeattributes (New RouteValueDictionary (htmlattributes));            Add Style            Builder. addCssClass (CSS);            Or in the form of the following sentence: Builder. Mergeattribute ("class", CSS);            Add content, the following two ways can be            //builder. InnerHtml = text;            Builder. Setinnertext (text);            Output control            return builder. ToString (Tagrendermode.normal);        }

    On the page, call this method:

    <% =html.span ("Span.test", "using Tagbuilder to help build extension method", "colorred", new {style= "font-size:15px;"}) %>

    The generated HTML code is:

    <span id= "Span-test" class= "colorred" style= "font-size:15px;" > Using Tagbuilder to help build extension methods </span>

Using HTML helper classes to extend HTML controls in MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.