ASP.NET MVC中HTML元素的ID生成

Ale*_*yin 12 asp.net-mvc

我需要在asp.net mvc应用程序中为html元素生成唯一标识符.在经典的asp.net我可以使用

<a id=<%=ClientID>%>
Run Code Online (Sandbox Code Playgroud)

在asp.net mvc世界中有一些模拟?

更新:

例如,我想制作一个可重复使用的Button元素.我希望代码看起来类似于

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

如果ClientId不可用,那么最好的方法是什么?现在,我看到两个选项 - 像Guid.NewGuid()一样生成它还是从外面传递id?还有其他选择吗?

更新: 现在,我来看下面的解决方案

    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
        }
    }
Run Code Online (Sandbox Code Playgroud)

Zai*_*sud 15

使用内置.NET库的最简单正确的解决方案,无需新的自定义应用程序代码

使用Guid.NewGuid(),使用ToString()数字表示"N",以防止可能浏览JS问题的无效字符.

Guid.NewGuid().ToString("N");
Run Code Online (Sandbox Code Playgroud)

引用有关"N"格式说明符的MSDN :

32 digits: 00000000000000000000000000000000

不要使用默认的GUID表示,因为在JS/jQuery中使用连字符可能会有问题.

为了完整起见,最好在GUID的开头添加一个字母.虽然我从未在现代浏览器中遇到过这方面的问题,但从技术上讲,HTML id必须以字母而不是数字开头.


SLa*_*aks 1

对此没有单一的解决方案。

您需要修改代码以根据生成元素的内容生成 ID。

例如,如果要循环数据库中的行,则可以使用行的主键来生成 ID。

或者,您可以完全避开 ID 并使用非唯一的类。(这对于 jQuery 和后代选择器来说特别方便)