如何为用户控件内的控件生成唯一ID

时间:2013-10-07 12:41:34

标签: c# asp.net c#-4.0 user-controls

我有一个用户控件,其中有一个标签。

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

我使用此函数从代码后面渲染给定的UC:

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();
}

渲染后,我将其作为输出字符串:

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

现在,当我放置相同用户控件的两个实例时,我在输出字符串中得到相同的span ID。

我想为两个用户控件实例生成两个不同的ID。我该如何生成它?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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