2012-05-31 12 views
1

我使用這篇文章來創建圖像幫助程序: http://www.asp.net/mvc/tutorials/older-versions/views/using-the-tagbuilder-class-to-build-html-helpers-cs。它說它取代了時期,但沒有提到其他限制。在TagBuilder.GenerateID中使用GUID字符串

這一切工作正常,除非我嘗試使用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 

使用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 

有一些使用GUID字符串作爲ID時的限制或解決方法?

+0

Guid不是一個字符串,它是一個結構體。嘗試Guid.ToString('N'),給你一個沒有大括號或連字符的字符串 –

回答

5

ID必須以字母開頭,而不是數字。通常,GUID將以數字開頭,因此是問題所在。 TagBuilder.GenerateId調用CreateSanitizedId,執行此檢查:

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

最好的辦法是隻需添加一個前綴,如「GUID」或類似的ID的開始。

+0

+1我喜歡那個 - 我的意思是前綴 - 簡單的解決方案是最好的呃? –

+0

@PreetSangha當然。感謝一羣柯克,我想我從來沒有嘗試過用一個數字開始一個ID開始。 –