Click here to Skip to main content
Click here to Skip to main content

Custom HTML Extensions for MVC3

By , 19 Jun 2012
 

Introduction

In this article, I am going to share my experience in creating Html extensions for ASP.NET MVC3 Razor. At the end of the article, you will learn something new on how to create custom extension methods and its advantages. 

This is part one of two that I want to share with you.

Background 

This article is meant for an intermediate / experienced programmer who has some experience in developing applications in MVC3 Razor/Aspx.

There are two ways of creating Html extensions:

  1. With Extension methods
  2. Creating a cshtml file with all the logic. Either we can code with @helper or Razor and/or Html. Then pre-compile it to generate a DLL.

With Extension Method 

These extensions are written from scratch extensively using code. Here’s one sample example of how you can create an Html extension which outputs a Video tag for HTML5. You have to create a ClassLibrary project. Create a static class say ViedoExtension and copy the below mentioned code.

If your browser is supporting HTML5, then you should be able to see a video tag, else you will see a message ‘Your browser doesn't support video tags.

public static class VideoExtension
{
        public static MvcHtmlString Video
		(this HtmlHelper html, string src, bool showControls)
        {
            string url = UrlHelper.GenerateContentUrl(src, html.ViewContext.HttpContext);
            var tag = new TagBuilder("video") 
              {InnerHtml = "Your browser doesn't support video tags."};

            tag.MergeAttribute("src", url);
            if(showControls)
            // Show Play/Pause buttons
                tag.MergeAttribute("controls", "controls"); 
            return MvcHtmlString.Create(tag.ToString());
        }
}

With Helper method 

Your cshtml either can have @helper or just a code with razor syntax. Create a Class library project and a new razor cshtml file. Copy paste the below mentioned snippet for generating the list with <li>.

@helper WriteList(string[] items) 
{
     @foreach (var s in items)<ul>{
            <li> 
               @s  
            </li> 
}      </ul>}   

There is no way to reuse this cshtml unless you precompile this code to generate a DLL. We will next see how to re-compile the above one.

  1. Go to the VS Extension Gallery, it is under Tool in VS. Then install the Razor Single File Generator.

    MVC3CustomControl/razortocode.png

  2. Under the cshtml file -> properties, set the Build Action to Content, and set the custom tool to MVCRazorClassGenerator.
  3. Compile the Class library so that you will now see the *.cs file for the corresponding cshtml file under cshtml file.
  4. Do some minor tweaks. Say renaming the class name of *.cs file or extracting the core logic to a method.
  5. @{
        ViewBag.Title = "Sample code to demonstrate the usage of Custom Controls";
        var obj = new WriteToList();
        var str = new string[2]
                           {
                               "Test",
                                "Ranjan"
                           };
    } 
    @using (Html.BeginForm())
    {            
       @obj.WriteList(str)         
    }

Points of Interest

It’s very interesting and fun to create an Html extension method. I feel the second approach is really faster than the first one as we are more comfortable in writing cshtml. Wait for part two that I will be sharing with you soon.

Advantages  

Custom code in a library project makes it easy to produce a binary that can be used in multiple projects without having to keep source files around.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ranjan.D
Web Developer
United States United States
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1mvpMarcus Kramer25-Jan-13 4:34 
Question[My vote of 1] OMG this is just awefulmvpSacha Barber14-Jun-12 21:49 
AnswerRe: [My vote of 1] OMG this is just awefulmemberRanjan.D19-Jun-12 15:34 
GeneralMy vote of 3memberVitaly Tomilov14-Jun-12 0:43 
GeneralRe: My vote of 3mvpSacha Barber14-Jun-12 21:46 
QuestionModelsmemberMauxel16-Apr-12 0:38 
AnswerRe: ModelsmemberSeishin#13-Jun-12 22:01 
QuestionHow To use server control like @HTML.Textboxmembernageshwa18-Jan-12 23:55 
AnswerRe: How To use server control like @HTML.TextboxmemberSeishin#13-Jun-12 22:02 
GeneralRe: How To use server control like @HTML.TextboxmemberRanjan.D19-Jun-12 15:34 
QuestionTypo errormemberJamil Hallal18-Jul-11 1:49 
AnswerRe: Typo errormemberRanjan.D22-Jan-12 5:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 19 Jun 2012
Article Copyright 2011 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid