.NET Zone is brought to you in partnership with:

My name is Lohith G N. I am a Production Engg by education but a Software Engg by profession. I have an industry experience of 10 years in software development. I started with Web Application Development with ASP.NET 1.1 in 2001. Now have expertise in Web Application Development using ASP.NET Web Forms & ASP.NET MVC, Windows Application Development using Win Forms & WPF, Service Oriented Development with WCF. I have been awarded Microsoft Most Valuable Person in Oct 2011 for ASP.NET/IIS area and focus on Open Data Protocol or OData. Lohith is a DZone MVB and is not an employee of DZone and has posted 22 posts at DZone. You can read more from them at their website. View Full User Profile

HTML5 Placeholder Support for ASP.NET WebForm TextBox

02.05.2013
| 7530 views |
  • submit to reddit

Background:

In my last post “HTML5 Input Types Support in ASP.NET WebForm”, we looked at the HTML5 input types support from the ASP.NET WebForm TextBox control. One of the other cool features of HTML5 specification for a input controls is the placeholder attribute. Currently there is no support for placeholders in ASP.NET Webform TextBox control. In the blog post we will see how we can achieve this by creating a custom control.

What is a Placeholder:

According to the HTML5 Living Standard, the placeholder attribute is defined as follows:

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format. The attribute if specified, must have a value that contains no LINE FEED or CARRIAGE RETURN characters.

Here is the link to the living standard: http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-placeholder-attribute

Supporting Placeholder attribute in a TextBox – the Idea:

If we talk from a plain HTML perspective, in order to support the placeholder attribute, all we need to do is to add a attribute named “placeholder” and provide a value to that attribute on a INPUT control of type text. So here is how the HTML will look like:

<input  type="text" name="txtFirstName" id="txtFirstName" 
placeholder="enter first name" />

Now, we know that the ASP.NET WebForm TextBox control does not contain any property to support this. And all we have to do is to add an extra attribute on the input type control. So the idea to achieve this is as follows:

  • Create a custom web control which inherits from TextBox class
  • Add a public property of string type and name it “Placeholder”
  • Add attribute called placeholder during rendering of the control

We will look at the above steps one by one:

Creating Custom Web Control:

Open  visual studio and create a new project of type ASP.NET Server Control. I am selecting C# as the language.

SNAGHTML2e890245

By default, the project will contain a ServerControl1 class when the project is created. We will use the same class and modify the class name to suit to our needs. First, rename the class to lets say “HTML5TextBox”. Currently the class inherits from WebControl. Instead we will inherit the class from TextBox. This is because, we just want to subclass the TextBox and add an attribute just before rendering the user control. By doing this we get to use all the plumbing the TextBox control already provides in the control rendering. So now we have a HTML5TextBix control which inherits from TextBox. The code will look like below:

%MINIFYHTML38fd6b343119f51ea17a858296dc0bb23%
[DefaultProperty("Text")]
[ToolboxData("<{0}:Html5TextBox runat=server></{0}:Html5TextBox>")]
public class Html5TextBox : TextBox
{
  
}

Remove all other contents of the textbox for now. Lets get on with the next step which is creating a placeholder attribute.

Placeholder public property on the control:

Now that we have the class created, we will now expose a public property to set the placeholder text. This property will be set with a value in the page where this control will be consumed. If no placeholder value is set, the control will have a default value to set. Here is the property definition:

string _placeholder = "enter value";

[Bindable(true)]
[Category("Appearance")]
[DefaultValue("enter value")]
[Localizable(true)]
public string Placeholder
{
  get
    {
      return _placeholder;
    }

  set
    {
      _placeholder = value;
    }
}

As you can see, we have created a backing field and a public property to expose the Placeholder attribute. Next we will see how to add the attribute to the TextBox rendering.

Add Placeholder attribute while rendering TextBox control:

Now we have pretty much set up all the infrastructure needed to finish this. One thing we need to understand now is the rendering mechanism of a custom control. I suggest you read the following MSDN article to understand this: http://msdn.microsoft.com/en-us/library/aa338806(v=VS.71).aspx. So I will not be digging deep in to the rendering mechanism as that is out of this blog post scope.

As said in the idea section, we just want to include a custom attribute during the controls output rendering. The custom control infrastructure provides us with a hook for this. It is known as AddAttributesToRender method. Here is the official definition of this method:

image

The AddAttributesToRender() method gets a HtmlTextWriter and all we need to do is to use the AddAttribute() method on the writer to insert our custom attributes. Here is the code to perform this action:

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
  writer.AddAttribute("placeholder", _placeholder);
  base.AddAttributesToRender(writer);
}

As you can see we use the AddAttribute(string key, string value) overload to insert our custom attribute. the attribute name is “placeholder” and the value is what has been set in a page where the control is consumed.

Here is the complete code of the control:

[DefaultProperty("Text")]
    [ToolboxData("<{0}:Html5TextBox runat=server></{0}:Html5TextBox>")]
    public class Html5TextBox : TextBox
    {
        string _placeholder = "enter value";

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("enter value")]
        [Localizable(true)]
        public string Placeholder
        {
            get
            {
                return _placeholder;
            }
 
            set
            {
                _placeholder = value;
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute("placeholder", _placeholder);
            base.AddAttributesToRender(writer);
        } 
    }

Consuming the Custom Control:

In any ASP.NET WebForm project, add reference to the Custom Web Control library. Then in any webform i.e. lets say in Default.aspx, use the register tag to register the control first. Here is the register tag code:

<%@ Register  Assembly="HTML5WebFormsCustomControlLibrary" 
              Namespace="HTML5WebFormsCustomControlLibrary" 
              TagPrefix="kashyapa" %>

Next, just create the textbox control as usual. Here is the code to consume the custom control we just created:

<kashyapa:Html5TextBox  ID="txtName" 
                        runat="server" 
                        TextMode="SingleLine" 
                        Width="300px" 
                        Placeholder="enter your name">
</kashyapa:Html5TextBox>

<kashyapa:Html5TextBox  ID="txtEmailAddress" 
                        runat="server" 
                        Width="300px" 
                        TextMode="Email" 
                        Placeholder="enter your email address">
</kashyapa:Html5TextBox>

And here is the output of how the control will behave when rendered:

image

You can see that we now have the HTML5 placeholder as part of ASP.NET WebForm TextBox control. Similarly any other attributes which is not supported currently can be customized as we did for placeholder attribute.

Summary:

Being a stable platform, ASP.NET WebForm technology has a lot of hooks to quickly customize the controls according to our needs. We just saw how easy it is to customize a TextBox to add a HTML5 attribute named placeholder. In this way, even being in ASP.NET WebForm platform, we can start making our code HTML5 compliant.

PS: If anybody from Microsoft ASP.NET does come across this article, I would request them to see if the HTML5 attributes can be pushed into the TextBox control itself. That would void the above effort to support just an attribute and the TextBox will be able to support out of the box the HTML5 attributes. We will wait and watch Smile.

Published at DZone with permission of Lohith Nagaraj, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)