ID generation for HTML elements in ASP.NET MVC

后端 未结 4 901
刺人心
刺人心 2021-02-19 08:08

I need to generate unique identifiers for html elements in asp.net mvc application. In classic asp.net i could use

%>
         


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-19 08:36

    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.

提交回复
热议问题