Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ID generation for HTML elements in ASP.NET MVC

Tags:

asp.net-mvc

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

<a id=<%=ClientID>%>

Is there some analog in asp.net mvc world ?

UPDATE:

For example, I want to make a reusable Button element. I would perfer code to look similar to

<div class="myButton" id="<%=ClientID%>">
<script>
  var button = document.getElementById(<%=ClientID%>);
  button.onclick = ....
</script>

If ClientId is not available then what is the best way to follow ? For now, I see two options - to generate it like Guid.NewGuid() or pass id from the outside ? Any other options ?

UPDATE: For now, I've come to following solution

    public static string UniqueId(this HtmlHelper html)
    {
        var idGenerator = html.ViewContext.HttpContext.Items[typeof (UniqueIdGenerator)] as UniqueIdGenerator;
        if (idGenerator==null)
            html.ViewContext.HttpContext.Items[typeof (UniqueIdGenerator)] = idGenerator = new UniqueIdGenerator();
        return idGenerator.Next();
    }
       ...
    private class UniqueIdGenerator
    {
        private int id;

        public string Next()
        {
            id++;
            return "_c" + id; // todo: optimize
        }
    }
like image 973
Alex Ilyin Avatar asked Jun 27 '11 11:06

Alex Ilyin


2 Answers

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.

like image 83
Zaid Masud Avatar answered Oct 23 '22 05:10

Zaid Masud


There is no single solution to this.

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

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

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

like image 37
SLaks Avatar answered Oct 23 '22 06:10

SLaks