I need to generate unique identifiers for html elements in asp.net mvc application. In classic asp.net i could use
%>
Simplest correct solution using built-in .NET libraries with no new custom application code required
Use Guid.NewGuid(), with the ToString() numeric representation "N" in order to prevent invalid characters that could browser JS issues.
Guid.NewGuid().ToString("N");
Quoting MSDN regarding the "N"
format specifier:
32 digits: 00000000000000000000000000000000
Don't use the default GUID representation as hyphens can be problematic to work with in JS/jQuery.
For completeness, it's best prepend a letter to the beginning of the GUID. Although I've never experienced issues with this in modern browsers, technically an HTML id
has to begin with a letter and not a number.