2013-02-24 36 views
0

我的工作是用C#開發的一個項目,我的C#知識不豐富的,我剛開始學前幾天:)如何渲染HTML標記爲C#字符串

我遇到了這個功能:

public static IHtmlString RenderEditData<T>(string linkText) where T : CorinaEntity 
{ 
    string id = new IdGenerator().Generate<T>(); 

    return new HtmlString(String.Format("<a href=\"#\" data-corina='{{ \"id\" : \"{0}\", \"clrType\" : \"{1}\" }}'>{2}</a>", id, typeof(T).AssemblyQualifiedName, linkText)); 
} 

以上的回報我一個鏈接標籤,這是很好,當我第一次開始該項目的工作,但現在我只需要data屬性輸出爲字符串。所以,我只是嘗試這樣做:

public static String RenderEditData<T>() where T : CorinaEntity 
{ 
    string id = new IdGenerator().Generate<T>(); 


return String.Format("data-corina='{{ id : \'{0}\', 'clrType' : \'{1}\' }}", id, typeof(T).AssemblyQualifiedName); 
} 

的事情是,不是造成這樣的:

data-corina="{ "id" : "-[Model.Content]", "clrType" : "Model.Content, Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" }" 

它返回是這樣的:

data-corina="'{" id="" :="" &#39;-[model.content]&#39;,="" &#39;clrtype&#39;="" &#39;model.content,="" model,="" version="1.0.0.0," culture="neutral," publickeytoken="null'" }="" 

顯然,有一些字符串轉義是我做錯了,但我不知道如何去做,而不是搞亂我需要的變量。有人能爲我指出正確的解決方案嗎?如果我想改變public static IHtmlString RenderEditDatapublic static String RenderEditData,如果我想要的結果只是一個字符串,我也做錯了嗎?

回答

2

使用Html.Raw助手輸出原始HTML。

另外,包裹在字符串中的HtmlString

public static String RenderEditData<T>() where T : CorinaEntity 
{ 
    string id = new IdGenerator().Generate<T>(); 

    return new HtmlString(
      string.Format("data-corina='{{ id : \'{0}\', 'clrType' : \'{1}\' }}", 
             id, 
             typeof(T).AssemblyQualifiedName)); 
} 
+0

我仍然得到一個奇怪的結果,並沒有像我第一次得到它時,它是一個標籤 – Roland 2013-02-24 20:12:22

+0

我不知道什麼「奇怪的結果」的意思,@羅蘭德 – Oded 2013-02-24 20:13:10

+0

有一些地方引號是不應該是,但我只是想,我錯過了整個對象周圍的包裝報價:''data-corina ='{{\「id \」:\「{0} \」,\「clrType \」:\「{1 } \「}}'」':) – Roland 2013-02-24 20:17:12

0

MVC將難逃你返回任何普通字符串。這就是爲什麼你的原始函數返回IHtmlString。當您返回HtmlString時,管道知道您確實希望結果包含原始HTML。