ID generation for HTML elements in ASP.NET MVC

Viewed 12708

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
        }
    }
4 Answers
Related