在TagBuilder.GenerateID中使用GUID字符串

Chr*_*s M 1 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我使用这篇文章来创建一个Image帮助器:http: //www.asp.net/mvc/tutorials/older-versions/views/using-the-tagbuilder-class-to-build-html-helpers-cs.它说它取代了时期,但没有提到其他限制.

除非我尝试使用GUID字符串作为id,否则一切正常.

剃刀代码:

@Html.Image(id, ....) //passes a GUID string to helper fine
Run Code Online (Sandbox Code Playgroud)

ImageHelper与网页描述完全一样:

builder.GenerateId(id);
//breakpoint after this shows the builder object 
//does not create an id attribute when id is a GUID string.
//using id.ToString() doesn't work for GUIDs either
Run Code Online (Sandbox Code Playgroud)

在MergeAttributes中使用GUID字符串可以正常工作:

builder.MergeAttribute("title", id); //the GUID string is img title no problem
builder.MergeAttribute("class", id); //the GUID string is class as expected 
Run Code Online (Sandbox Code Playgroud)

使用GUID字符串作为ID时是否存在某些限制或解决方法?

Kir*_*oll 5

ID必须以字母开头,而不是数字.通常,GUID将以数字开头,因此问题就出现了. TagBuilder.GenerateId调用CreateSanitizedId,执行此检查:

if (!TagBuilder.Html401IdUtil.IsLetter(c1))
    return (string) null;
Run Code Online (Sandbox Code Playgroud)

最好的办法是在ID的开头添加一个前缀,如"guid"或其他内容.