Asp.net mvc3 custom htmlhelper Control

Source: Internet
Author: User

In Asp.net MVC, every HTML Control Returns mvchtmlstring, which inherits htmlstring.
The following is a custom HTML Control for displaying male and female. You can directly call this custom HTML control when creating a page.
Other HTML controls return htmlhelper, therefore, the same type must be returned during customization.
Create an HTML control to be customized in the controls folder.
Code as follows:

Using system. web. MVC; using system. text; namespace system. web. MVC. HTML {// <summary> /// display the customized control of gender and gender // </Summary> Public static class labelgenderextensions {// <summary> // obtain the value hour: 1 indicates male, the value is 2, indicating female /// the selected male /// </Summary> /// <Param name = "helper"> </param> /// <returns> </returns> Public static mvchtmlstring labelgender (this htmlhelper helper) {stringbuilder STR = new stringbuilder (); Str. append ("<input type = 'Radio 'name = 'sex 'value = 1 checked = 'checked'> </input>"); Str. appendformat ("<label for = '{0}'> {1} </label>", "man", "male"); // display the male value Str. append ("<input type = 'Radio 'name = 'sex' value = 2> </input>"); Str. appendformat ("<label for = '{0}'> {1} </label>", "female", "female "); // display female value return New mvchtmlstring (Str. tostring ());}}}

The value to be returned can also be passed in according to the parameter method.

On the page, you only need to call: @ html. labelgender ()

Display

Note:
1. Note that the namespace for creating a class must be consistent with its @ html

2. The created class must be a static class. The naming rule is generally suffixed with extensions.

The htmlhelper control can be expanded to provide great convenience for creating your own HTML tags.

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.