I need to generate unique identifiers for html elements in asp.net mvc application. In classic asp.net i could use
%>
I liked the answer you provided in your Update better than using a Guid
, because the latter will be different each time which makes client-side debugging and finding an element in View Source more difficult.
I took it a step further and added a custom prefix
.. each prefix
uses its own counter to help even further in that regard.
public static string GetUniqueHtmlid(this HtmlHelper html, string prefix)
{
var generator = html.ViewContext.HttpContext.Items[typeof (UniqueHtmlIdGenerator)] as UniqueHtmlIdGenerator;
if(generator == null)
html.ViewContext.HttpContext.Items[typeof(UniqueHtmlIdGenerator)] = generator = new UniqueHtmlIdGenerator();
return generator.GetNextUniqueId(prefix);
}
private class UniqueHtmlIdGenerator
{
private readonly Dictionary _items = new Dictionary();
public string GetNextUniqueId(string prefix)
{
if (string.IsNullOrEmpty(prefix))
prefix = "item";
int current;
lock (typeof (UniqueHtmlIdGenerator))
{
current = _items.ContainsKey(prefix) ? _items[prefix] : 1;
_items[prefix] = current + 1;
}
return string.Format("{0}-{1}", prefix, current);
}
}