在 TagBuilder.GenerateID 中使用 GUID 字符串



我用这篇文章创建了一个图像助手: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

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

在合并属性中使用 GUID 字符串工作正常:

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

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

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

if (!TagBuilder.Html401IdUtil.IsLetter(c1))
    return (string) null;

最好的办法是添加一个前缀,如"guid"或其他东西到ID的开头。

最新更新