ASP.NET MVC中HTML元素的ID生成 [英] ID generation for HTML elements in ASP.NET MVC

查看:110
本文介绍了ASP.NET MVC中HTML元素的ID生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<a id=<%=ClientID>%>

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

Is there some analog in asp.net mvc world ?

更新:

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

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>

如果ClientId不可用,那么遵循的最佳方法是什么? 现在,我看到两个选项-生成 Guid.NewGuid()之类的代码还是从外部传递ID?还有其他选择吗?

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
        }
    }

推荐答案

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

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

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

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

用MSDN引用"N"格式说明符:

Quoting MSDN regarding the "N" format specifier:

32 digits: 00000000000000000000000000000000

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

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

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

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.

这篇关于ASP.NET MVC中HTML元素的ID生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆