How to create custom HTML helper in Asp.net MVC 3 or 4

Source: Internet
Author: User
ArticleDirectory
    • How to write your own HTML helper methods?

I will try to show you a basic feature of ASP. net MVC, creating custom HTML helpers. we can reduce the amount of logic in view pages (razor or Asp.net-aspx-pages) by extracting logic code as method.

HTML helper methods are nothing more than methods that are returning string. if you want to write your own HTML helper method you have to write extension methods for htmlhelper class. ASP. net MVC framework itself contains extension methods for htmlhelper class to have well structured helper Methods separation. ASP. net MVC Framework HTML helper extension methods are located undersystem. web. MVC. HTML namespace.

How to write your own HTML helper methods?

Razor pages uses system. web. MVC. webviewpage type as base class. razor pages automatically inherits from this type, if you want to see the configuration or if you want to replace it with your base class you shocould check web. config file in your asp. net MVC project. this subject is not in this article's context but if you want to use your own base class, you can create a new class which inherits from webviewpage and you can edit web. config File with your type name.

I mentioned that HTML helper methods are extension methods for htmlhelper classes (one is generic, one is plain old class ). so, we can write extension methods to use them inside razor pages but how does it happen?

As you can see from above screenshot webviewpage has a property named HTML and this property type is system. Web. MVC. htmlhelper <t>.

And we can access this type and it's member from razor pages. (see below)

It seems we can add our extension methods and access that methods from razor Page Markup. let's create our first extension methods. you can add a new class file and write your own extension method, there is no difference than normal C # extension methods.

I created a file named htmlhelperextensions. CS and added two basic HTML helper method.

Using system. web. MVC; namespace extensions {public static class htmlhelperextensions {private const string nbsp = ""; private const string selectedattribute = "selected = 'selected'"; public static mvchtmlstring nbspifempty (this htmlhelper helper, string Value) {return New mvchtmlstring (string. isnullorempty (value )? Nbsp: value);} public static mvchtmlstring selectedifmatch (this htmlhelper helper, object expected, object actual) {return New mvchtmlstring (equals (expected, actual )? Selectedattriy: String. Empty );}}}

Two extesion methods, one is nbspifempty, it checks the given value and if it's empty returns & nbsp;, if it is not returns the given value. second one is return selected Attribute if criteria matches.

Let's try to use this HTML helpers methods from your razor page. it will not work because we need to add our HTML helper class to the razor pages. it is same thing to adding a "using" statement to C # classes to use extension methods. open your web. config File and add namespace of your new class which contains your extension methods.

<System. Web. webpages. Razor>  "  System. Web. MVC. mvcwebrazorhostfactory, system. Web. MVC, version = 3.0.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35  " /> <Pages pagebasetype = "  System. Web. MVC. webviewpage  " > <Namespaces> <addNamespace = "  System. Web. MVC  " /> <Add Namespace = "  System. Web. MVC. Ajax  " /> <Add Namespace = "  System. Web. MVC. html  " /> <Add Namespace = " System. Web. Routing  " /> <Add Namespace = "  Mvchtmlhelpers  " /> </Namespaces> </pages> </system. Web. webpages. Razor>

I want to show using of second HTML helper. First select element contains and embedded if statement inside markup which doesn't seem a good. Right?

  select   @ foreach (  var  item  in   viewbag. items) {  viewbag. selecteditem) {@ mvchtmlstring. create (  "  selected = 'selected'  "  ) }>@ item. itemname  } 
   select  

If we use our HTML helper methods to make option element selected markup code seems better. (viewbag. selecteditem is an dynamic data for this sample razor page and comes from controller. if item. itemname equals this value option element will be selected.

 
<Select>@ Foreach (VaRItemInViewbag. Items ){<Option@Html.SelectedIfMatch ((String) Viewbag. selecteditem ,(String) Item. itemname)> @ item. itemname </option>}</Select>

This is a very basic sample for HTML helpers but you should look for possibilities of extract your logic from razor pages to HTML helpers.

 

 

Related Article

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.