The HtmlHelper helper method of MVC extension

Source: Internet
Author: User

1, what is the HtmlHelper auxiliary method? is actually the extension method of the HtmlHelper class, as follows:

Namespacesystem.web.mvc.html{PublicStaticClass FormExtensions//Form-related extension methods, such as creating form labels, and so on.PublicStaticClass InputExtensions//All input is included here, for example: Text,button,readiobutton and so on.PublicStaticClass Linkextensions//Link related methodsPublicClass Mvcform:idisposable//public static class renderpartialextensions//  This is the output partialview public static class selectextensions // output drop-down box public static class textareaextensions// output multiline text box public static // output related form element validation. } 

For example, the extended class INPUTEXTENSIONS,MVC framework itself has an extension for this:

namespace system.web.mvc.html{    // Summary:    //classstatic Mvchtmlstring CheckBox (string name);
}
}

2, through the expansion of HtmlHelper to build their own htmlhelper auxiliary method

System.Web.Mvc.Html under the HtmlHelper can only complete most of the HTML control output, some of the things we often use it does not, how to do? Do It yourself ~

Before we expand, there's a class called Tagbuilder (Generate tags) that works better, and you don't have to dwell on its details, as long as you know that he has those methods:

Public Tagbuilder (StringTagName);Publicvoid addCssClass (String value);//Add StylePublicvoid Generateid (string name);//Set the control IDPrivateStringGetattributesstring ();Publicvoid Mergeattribute (String key,String value);//Setting property valuesPublicvoid Mergeattribute (String key,String value,boolreplaceexisting);Publicvoid Mergeattributes<tkey, tvalue> (Idictionary<tkey, tvalue>attributes); public void Mergeattributes<tkey, tvalue> (Idictionary<tkey, tvalue> attributes, bool  replaceexisting); public void Setinnertext (string innerText);  sets the display text public  override string ToString (); public string ToString (Tagrendermode rendermode);  Output Control HTML                 

Now it's time to start expanding!

A, extended img Tag

Namespacesystem.web.mvc{PublicStaticClassimageextensions {PublicStaticString Image (This HtmlHelper helper,String ID,String URL,StringAlternateText) {Return Image (helper, id, url, alternatetext,Null); }PublicStaticString Image (This HtmlHelper helper,String ID,String URL,String AlternateText,ObjectHtmlattributes) {//Create an IMG tagvar builder =New Tagbuilder ("Img");// builder. Generateid (ID); // add Property Builder. Mergeattribute ( "src" , URL); Builder. Mergeattribute ( "alt" new RouteValueDictionary ( Htmlattributes)); // output full img tag return< Span style= "color: #000000;" > Builder. ToString (tagrendermode.selfclosing); } }} 

Call: @Html. Image ("Img1", http://img/111.jpg, "This is a picture", new {border= "4px"})

Output: http://img/111.jpg" style= "BORDER:4PX;" alt= "This is a picture"/>

B, Extended div tag

Namespacesystem.web.mvc{PublicStaticClassdivextensions {PublicStatic String Div (This htmlhelper helper, string ID, string content, String CSSStyle,Objecthtmlattrs) {Tagbuilder builder =New Tagbuilder ("div"); // replace "." To "_" builder. Idattributedotreplacement = "_"; Builder. Generateid (ID); Builder. Mergeattributes (new routevaluedictionary (htmlattrs)); builder. addCssClass (CSSStyle); Builder. innerhtml=content; return builder. ToString (Tagrendermode.normal); // represents a double-  sided label               }}} 

Call:

@Html. Div ("Mydiv.1", "extension method", "Myclassstyle", new {style= "Border:solid red 1px;"})

Output:

<div id= "mydiv_1" class= "Myclassstyle" style= "Border:solid red 1px;" > Extension Methods </div>

C. Extending the Span label

Namespacesystem.web.mvc{PublicStaticClassspanextensions {PublicStaticString Span (This HtmlHelper helper,String ID,String text,String css,ObjectHtmlattributes) {//Creative Tagbuilder of a certain tagvar builder =New Tagbuilder ("Span");//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 are available //builder. InnerHtml = text; Builder. Setinnertext (text); // Output control return builder. ToString (Tagrendermode.normal); } }}

Call:

@Html. Span ("Span.test", "use Tagbuilder to help build extension method", "colorred", new {style="font-size:15px;"})

Output:

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

D, extended UL, Li label

Namespacesystem.web.mvc{PublicStaticClassulliextensions {PublicStatic Mvchtmlstring Ulli (This HtmlHelper helper, string[] listItems) {Tagbuilder Ultag = new Tagbuilder (ul" Span style= "color: #000000;" >); foreach (string item in  ListItems) {Tagbuilder Litag = new Tagbuilder ( "li "); Litag.setinnertext (item); ultag.innerhtml += litag.tostring ();} return new 

Call:

@Html. List (New string[]{"Shanghai", "Shenzhen", "Beijing", "Guangzhou"})

Output:

<ul> <li> Shanghai </li> <li> shenzhen </li> <li> Beijing </li> <li> Guangzhou </li>  </ul>

E, Extended intercept string method (when we display a field, if it is too long, it is best to intercept when the display, it is best to make an extension method to use)

Namespacesystem.web.mvc{PublicStaticClass Cutstringextensions {public static string cutstring ( this System.Web.Mvc.HtmlHelper Helper, string content, int Length "{if ( Content. Length > length) {return content. Substring (0, length) +  "  ...  ";} else {return content; } } }} 

Here is just a point, more usage to be developed according to actual needs ~

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.