为ASP中的HTML元素生成ID。NET MVC

时间:2021-01-27 03:27:17

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

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

<a id=<%=ClientID>%>

Is there some analog in asp.net mvc world ?

在asp.net mvc世界中有类似的东西吗?

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 ?

如果ClientId不可用,那么最好的方法是什么?现在,我看到了两个选项——生成它,比如guide . newguid()还是从外部传递id ?其他选项吗?

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 个解决方案

#1


15  

Simplest correct solution using built-in .NET libraries with no new custom application code required

最简单的正确解决方案,使用内置的。net库,不需要新的自定义应用程序代码

Use Guid.NewGuid(), with the ToString() numeric representation "N" in order to prevent invalid characters that could browser JS issues.

newguid(),使用ToString()数字表示“N”,以防止可能出现浏览器JS问题的无效字符。

Guid.NewGuid().ToString("N");

Quoting MSDN regarding the "N" format specifier:

引用MSDN关于“N”格式说明符:

32 digits: 00000000000000000000000000000000

32位数字:00000000000000000000000000000000

Don't use the default GUID representation as hyphens can be problematic to work with in JS/jQuery.

不要使用默认的GUID表示,因为在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.

为了完整起见,最好把信放在GUID开头。虽然在现代浏览器中我从未遇到过这样的问题,但从技术上讲,HTML id必须以字母开头,而不是数字。

#2


1  

There is no single solution to this.

没有单一的解决办法。

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

您需要修改代码,以基于生成元素的内容生成id。

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

例如,如果您正在对来自数据库的行进行循环,您可以使用行的主键来生成id。

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

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

#3


1  

I liked the answer you provided in your Update better than using a Guid, because the latter will be different each time which makes client-side debugging and finding an element in View Source more difficult.

与使用Guid相比,我更喜欢您在更新中提供的答案,因为后者每次都会有所不同,这使得客户端调试和在视图源代码中查找元素变得更加困难。

I took it a step further and added a custom prefix.. each prefix uses its own counter to help even further in that regard.

我更进一步,添加了一个自定义前缀。在这方面,每个前缀都使用自己的计数器来进一步帮助。

    public static string GetUniqueHtmlid(this HtmlHelper html, string prefix)
    {
        var generator = html.ViewContext.HttpContext.Items[typeof (UniqueHtmlIdGenerator)] as UniqueHtmlIdGenerator;

        if(generator == null)
            html.ViewContext.HttpContext.Items[typeof(UniqueHtmlIdGenerator)] = generator = new UniqueHtmlIdGenerator();

        return generator.GetNextUniqueId(prefix);
    }

    private class UniqueHtmlIdGenerator
    {
        private readonly Dictionary<string, int> _items = new Dictionary<string, int>();

        public string GetNextUniqueId(string prefix)
        {
            if (string.IsNullOrEmpty(prefix))
                prefix = "item";

            int current;

            lock (typeof (UniqueHtmlIdGenerator))
            {
                current = _items.ContainsKey(prefix) ? _items[prefix] : 1;

                _items[prefix] = current + 1;
            }

            return string.Format("{0}-{1}", prefix, current);
        }
    }

#4


-1  

May be this draft code help you:

这段代码草案可能对您有所帮助:

static class MyIdGenerator
{
    public static int NextID()
    {
        static int _id = 0;
        return _id++;
    }
}

With static counter every call NextID() will return next Id;

使用静态计数器,每个调用NextID()将返回下一个Id;

#1


15  

Simplest correct solution using built-in .NET libraries with no new custom application code required

最简单的正确解决方案,使用内置的。net库,不需要新的自定义应用程序代码

Use Guid.NewGuid(), with the ToString() numeric representation "N" in order to prevent invalid characters that could browser JS issues.

newguid(),使用ToString()数字表示“N”,以防止可能出现浏览器JS问题的无效字符。

Guid.NewGuid().ToString("N");

Quoting MSDN regarding the "N" format specifier:

引用MSDN关于“N”格式说明符:

32 digits: 00000000000000000000000000000000

32位数字:00000000000000000000000000000000

Don't use the default GUID representation as hyphens can be problematic to work with in JS/jQuery.

不要使用默认的GUID表示,因为在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.

为了完整起见,最好把信放在GUID开头。虽然在现代浏览器中我从未遇到过这样的问题,但从技术上讲,HTML id必须以字母开头,而不是数字。

#2


1  

There is no single solution to this.

没有单一的解决办法。

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

您需要修改代码,以基于生成元素的内容生成id。

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

例如,如果您正在对来自数据库的行进行循环,您可以使用行的主键来生成id。

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

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

#3


1  

I liked the answer you provided in your Update better than using a Guid, because the latter will be different each time which makes client-side debugging and finding an element in View Source more difficult.

与使用Guid相比,我更喜欢您在更新中提供的答案,因为后者每次都会有所不同,这使得客户端调试和在视图源代码中查找元素变得更加困难。

I took it a step further and added a custom prefix.. each prefix uses its own counter to help even further in that regard.

我更进一步,添加了一个自定义前缀。在这方面,每个前缀都使用自己的计数器来进一步帮助。

    public static string GetUniqueHtmlid(this HtmlHelper html, string prefix)
    {
        var generator = html.ViewContext.HttpContext.Items[typeof (UniqueHtmlIdGenerator)] as UniqueHtmlIdGenerator;

        if(generator == null)
            html.ViewContext.HttpContext.Items[typeof(UniqueHtmlIdGenerator)] = generator = new UniqueHtmlIdGenerator();

        return generator.GetNextUniqueId(prefix);
    }

    private class UniqueHtmlIdGenerator
    {
        private readonly Dictionary<string, int> _items = new Dictionary<string, int>();

        public string GetNextUniqueId(string prefix)
        {
            if (string.IsNullOrEmpty(prefix))
                prefix = "item";

            int current;

            lock (typeof (UniqueHtmlIdGenerator))
            {
                current = _items.ContainsKey(prefix) ? _items[prefix] : 1;

                _items[prefix] = current + 1;
            }

            return string.Format("{0}-{1}", prefix, current);
        }
    }

#4


-1  

May be this draft code help you:

这段代码草案可能对您有所帮助:

static class MyIdGenerator
{
    public static int NextID()
    {
        static int _id = 0;
        return _id++;
    }
}

With static counter every call NextID() will return next Id;

使用静态计数器,每个调用NextID()将返回下一个Id;