[ACCEPTED]-ID generation for HTML elements in ASP.NET MVC-asp.net-mvc

Accepted answer
Score: 20

Simplest correct solution using built-in .NET libraries with no new custom application code required

Use Guid.NewGuid(), with the ToString() numeric representation 10 "N" in order to prevent invalid 9 characters that could browser JS issues.


Quoting 8 MSDN regarding the "N" format specifier:

32 digits: 00000000000000000000000000000000

Don't 7 use the default GUID representation as hyphens 6 can be problematic to work with in JS/jQuery.

For 5 completeness, it's best prepend a letter 4 to the beginning of the GUID. Although I've 3 never experienced issues with this in modern 2 browsers, technically an HTML id has to begin with a 1 letter and not a number.

Score: 1

There is no single solution to this.

You 8 need to modify your code to generate IDs 7 based on whatever is generating the elements.

For 6 example, if you're looping over rows from 5 a database, you can use the rows' primary 4 keys to generate IDs.

Alternatively, you 3 can eschew IDs altogether and use non-unique 2 classes. (this is especially convenient 1 with jQuery and descendant selectors)

Score: 1

I liked the answer you provided in your 7 Update better than using a Guid, because the 6 latter will be different each time which 5 makes client-side debugging and finding 4 an element in View Source more difficult.

I 3 took it a step further and added a custom 2 prefix.. each prefix uses its own counter to help even 1 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<string, int> _items = new Dictionary<string, int>();

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

More Related questions