Custom HtmlHelper and mvchtmlhelper in ASP. NET MVC
Preface
The HtmlHelper method provides us with a lot of html tags. You only need to call them on the page. However, Microsoft does not apply all html tags to the extension method. You need to customize Htmlper, to meet our needs.
Method
Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; namespace TestMvcHelper {public static class HtmlExtensions {public static MvcHtmlString Submit (this HtmlHelper helper, string value) {var builder = new TagBuilder ("input "); // set the tag name we created to input builder. mergeAttribute ("type", "submit"); // Add attribute type = "submit" builder. mergeAttribute ("value", value); return MvcHtmlString. create (builder. toString (TagRenderMode. selfClosing ));}}}
Interpretation of the code above:
- When using TagBuilder, you must introduce the namespace System. Web. Mvc.
- The Submit method name corresponds to the name called in the attempt. (For example, @ Html. Submit ("Submit "))
- This HtmlHelper helper adds the Submit method to HtmlHelper, and value is the text on the submitted button passed in.
- Var builder = new TagBuilder ("input"); set the tag name to input.
- Builder. MergeAttribute ("type", "submit") sets the tag attribute type = "submit ".
- Builder. MergeAttribute ("value", value); set the Value of the tag submission button.
- TagRenderMode. SelfClosing indicates the mode used to display the auto-ending mark (for example, <input/>.
- TagRenderMode is an enumeration class, which is Normal (indicating the mode used to render Normal text) and StartTag (indicating the mode used to render the start tag (for example, <tag>), EndTag (indicating the mode used to present the end tag (for example, </tag>), SelfClosing (indicating the mode used to present the end tag (for example, <tag/> ).
- MvcHtmlString is used as the return value so that the return value is not escaped. For example, "<" is not converted to "& lt ".
Write the following code in View to call
@ Html. Submit ("Submit ")
Preview generated results
<Input type = "submit" value = "submit"/>
This article ends here. HtmlHelper contains many things, and some other things are not introduced. I will continue to learn some time. If you are interested, I can continue to expand. Welcome to the discussion. If you like it, we recommend it!