Introduction

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

It 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 Custom Controls

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.

Create Controls with Extension methods:

These are the controls written from the scratch extensively using code. Here’s one sample example of how to create a control which outputs a Video tag for HTML5. First you need to create a ClassLibrary project then create a static class say ViedoExtension. 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 does’nt support video tags.

public static class ViedoExtension
{
        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());
        }
}        

The static method of Video method returns an encoded string, so do not have to encode it again while using this extension. Here’s the usage in your web application: @Html.Video(“cat.avi”,true)

Creating a custom control with the help of *.cshtml

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 past 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.

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.

@{
    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 Custom control. 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 of creating a Custom control

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
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"