简体   繁体   中英

how can I wrap a control with a div from the code behind in asp.net?

Is it possible to add a div tag that can wrap a control from the behind? I want to send a list of controls to my function and have it dynamically add a div around each one, so that each control is within its own div.

Example: html:

...
<p> some text</p>
Name: <asp:textbox id="txtName" runat="server" />
...

function should work to make the markup look like this-

...
<p> some text</p>
Name: <div id="divName" runat="server"><asp:textbox id="txtName" runat="server" /></div>
...

Yes, and there is more than one way to do this.

Recommended solution: create a custom control

You can easily create a custom control that extends System.Web.UI.WebControls.TextBox and overrides the Render method to write the markup for you. This gives you ultimate flexibility in how a control is rendered. This example uses base.Render() to render the TextBox itself, but wraps it in a DIV by writing directly to the HtmlTextWriter . The major benefits to this are that your custom control will be available in the code behind just like any other server control and that you can declare it in your .aspx/.ascx files.

To wit:

public class WrappedTextBox : System.Web.UI.WebControls.TextBox
{
    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write("<div id=\"div{0}\" runat=\"server\">", this.ID.Replace("txt", String.Empty));
        base.Render(writer);
        writer.WriteEndTag("div");
    }
}

To use the control in an ASPX page, first Register the control's namespace:

<%@ Register Assembly="WebApplication1" TagPrefix="cc" Namespace="WebApplication1" %>

Then add the control to your form like so:

<cc:WrappedTextBox ID="txtName" runat="server" Text="Wrapped!" />

cc is just an arbitrary prefix that I chose, but you can make up your own! ( cc for "custom control")

Note that the runat=\\"server\\" is probably unnecessary in the div output (though you could be writing code that generates ASPX content, I suppose). The runat="server" just tells ASP.NET that you want it to be a server control, but in this case your WrappedTextBox is the server control. Also note that this isn't necessarily a best-practices example.. I wouldn't replace the txt normally, but rather would use a custom attribute for the div ID. (But this example will give the requested output.)

Alternate solution: Depth first search and modification of the Control Tree

    protected void Page_Load(object sender, EventArgs e)
    {
        DeepControlSearch(Page);
    }
    private void DeepControlSearch(Control control)
    {
        if (control.HasControls())
        {
            for (int c = control.Controls.Count - 1; c > -1; c--)
            {
                DeepControlSearch(control.Controls[c]);
            }
        }
        if (control is TextBox)
        {
            WrapTextBox((TextBox)control);
        }
    }
    private void WrapTextBox(TextBox textBox)
    {
        System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
        div.ID = String.Format("div{0}", textBox.ID.Replace("txt", String.Empty));
        div.Attributes["runat"] = "server";
        Control parent = textBox.Parent;
        parent.Controls.Remove(textBox);
        div.Controls.Add(textBox);
        parent.Controls.Add(div);
    }

The benefit to this approach is that you don't have to create custom controls (which requires a bit of up-front work, but usually is a worthwhile investment because you can reuse them in any ASP.NET project). The HtmlGenericControl can be manipulated like any other server control, but it is dynamic and so needs to be in ViewState if you want to access it on PostBack (unless you want to do it the oldskool way and loop through the posted Form elements to get values from dynamic controls).

Not sure I would recommend the second approach; this is really what custom controls are made for.

Alternate solution #2: emit JavaScript (jQuery makes it really easy) to wrap the controls

You could use ClientScript.RegisterStartupScript() to emit some JavaScript or jQuery to do this, for example:

ClientScript.RegisterStartupScript(
    this.GetType(),
    "wrap textboxes",
    "$(document).ready(function(){$('input:text').each(function(){$(this).wrap('<div id=\"div' + this.id.replace('txt', '') + '\"></div>');});});",
    true);

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