2010-10-22 95 views
2

我想允許在評論框中使用HTML(最終使用tinymce或類似的東西),將其存儲在MSSQL數據庫中,然後將其讀回頁面,其中字段呈現在tabl單元格中。使用ASP.NET MVC在數據庫中存儲和讀取HTML?

在我修復了操作方法的驗證問題後,這一切都可以正常工作。但是當從數據庫中讀回時,它會呈現HTML標籤可見的文本,而不是格式化的HTML。即如果我看的HTML源代碼中的表,它是這樣的:

 <td> 
      &lt;p&gt;Testing HTML&lt;/p&gt;&lt;p&gt;Hope it works&lt;/p&gt; 
     </td> 

那麼,如何呈現爲格式化的文本?當我這樣做來驗證驗證時,我只是在textarea的標籤中寫下了。

回答

2

Professional ASP.NET MVC提供有關 「代碼掘金」 的差異這樣的解釋:

當我們看Details.aspx 模板更加緊密,我們會發現它包含了靜態HTML以及 作爲嵌入式呈現代碼 。當查看 模板呈現<%%>代碼 冰渣執行代碼,並<%:%>代碼 熔核執行的代碼包含在其中 然後渲染結果 到模板的輸出流。

在這個描述中忽略了<%=%>中的代碼塊是如何工作的。 Scott Guthrie在他的文章New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)中描述了這個區別。 Phil Haack在關於以Html Encoding Code Blocks With ASP.NET 4開頭的HTML編碼塊的系列文章中更詳細地討論了這一點。

你發現的是,<%=%>將原始HTML文件輸出到輸出流中,而<%:%>執行HTML編碼。

+0

感謝您的鏈接! – Anders 2010-10-23 20:28:27

0

你想HtmlDecode

爲了給MSDN例如

HttpUtility.HtmlDecode方法

using System; 
using System.Web; 
using System.IO; 

    class MyNewClass 
    { 
     public static void Main() 
     { 
     String myString; 
     Console.WriteLine("Enter a string having '&' or '\"' in it: "); 
     myString=Console.ReadLine(); 
     String myEncodedString; 
     // Encode the string. 
     myEncodedString = HttpUtility.HtmlEncode(myString); 
     Console.WriteLine("HTML Encoded string is "+myEncodedString); 
     StringWriter myWriter = new StringWriter(); 
     // Decode the encoded string. 
     HttpUtility.HtmlDecode(myEncodedString, myWriter); 
     Console.Write("Decoded string of the above encoded string is "+ 
         myWriter.ToString()); 
     } 
    } 
+0

那麼,我已經嘗試過,但它沒有奏效。但是也許我找到了答案:我用<%:item.Comment%>寫出了視圖中的文本。我猜想:即使我在控制器中使用了HtmlUtility.HtmlDecode,也會對其進行編碼。所以如果我改爲<%= item.Comment%>,它似乎工作。 – Anders 2010-10-22 10:44:00

相關問題