7

I have a User Control in which I have one label.

<asp:Label ID="lblProductionName" 
           runat="server" 
           Text="Production Name will come here">
</asp:Label>

I render the given UC from code behind using this function:

private string RenderControl(Control control)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(sw);

    control.RenderControl(writer);
    return sb.ToString();
}

After rendering, I get this as the output string:

<span id="lblProductionName">Production Name will come here</span>

Now, when I put two instances of the same User Control, I get the same span ID in the output string.

I want to generate two different IDs for two instances of User Control. How can I generate it?

4

2 回答 2

2

始终有效的选项是:Guid.NewGuid :)

于 2013-10-08T13:32:50.443 回答
0

你可以尝试这样的事情:

private Dictionary<string, int> controlInstances = new Dictionary<string, int>();

private string RenderControl(Control control)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(sw);

    int index = GetOrAddControlInstanceCount(control);

    control.ClientIDMode = ClientIDMode.Static;
    control.ID = control.GetType().Name + index;

    control.RenderControl(writer);

    return sb.ToString();
}

private int GetOrAddControlInstanceCount(Control control)
{
    string key = control.GetType().Name;

    if (!controlInstances.ContainsKey(key))
    {
        controlInstances.Add(key, 0);
    }

    return controlInstances[key]++;
}

更高级的解决方案可能是使用NamingContainer

于 2013-10-07T14:29:35.593 回答