简体   繁体   中英

How can I render a new property in an HTML Input from a Custom ServerControl in ASP.Net

I'm new to custom asp.net server controls and can't seem to find any examples of what I think should be a fairly easy task. I'm trying to write a custom textbox server control that allows me to pass in a new custom property called placeholder as follows:

<bs:BootstrapTextbox ID="BootstrapTextboxTest" CssClass="span2" placeholder="This is a Test" runat="server"></bs:BootstrapTextbox>

and render this:

<input name="BootstrapTextboxTest" type="text" id="BootstrapTextboxTest" class="span2" placeholder="This is a Test">

The placeholder tag is used within Twitter's Bootstrap JQuery framework to render text within the control. I would like to access it via my codebehind for localization.

Here is my custom server control at the moment:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BootstrapControls
{
public class BootstrapTextbox : TextBox
{
    [Bindable(false)]
    [Category("Properties")]
    [DefaultValue("")]
    [Localizable(true)]
    public string Placeholder
    {
        get
        {
            String placeholder = (String)ViewState["placeholder"];
            return ((placeholder == null) ? String.Empty : placeholder);
        }
        set
        {
            ViewState["placeholder"] = value;
        }
    }
    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.Write(Placeholder);
    }
  }
}

Again. I'm new to this, so any direction/examples would be greatly appreciated. Thanks in advance for any assistance.

Your approach looks fine and should work. Can you tell us if you are just confirming your approach before implementing it or facing any issue ?

OK, sorted it out. I didn't realize I simply needed to add my attribute and render it:

    protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
    {
        writer.AddAttribute("placeholder", Placeholder);
        base.AddAttributesToRender(writer);
    } 

Previously the placeholder attribute would not render in the HTML. Works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM