2014-01-24 29 views
1

我有存儲在長相酷似該數據庫中的某些HTML:寫HTML頁面中的MVC 4

<strong><a href="http://www.google.com" target="_blank">Maintenance scheduled </a></strong>tomorrow 

我想輸出正確格式爲HTML的Razor視圖。我不想看到<>,我只想要HTML。

你可以從這個片段,我已經嘗試了幾種不同的東西看:

div id="maintenanceMessage"> 
      @*@HttpUtility.HtmlDecode(sysSettings.MaintenanceMessage)*@ 
      @*@HttpUtility.HtmlDecode((new HtmlString(sysSettings.MaintenanceMessage)).ToString())*@ 
      @Html.Raw(sysSettings.MaintenanceMessage) 
</div> 

但在任何情況下它不斷顯示其文本:

<strong><a href="http://www.google.com" target="_blank">Maintenance scheduled </a></strong>tomorrow 

,而不是格式化的HTML。 我不確定我在做什麼錯?

回答

3

嘗試

@MvcHtmlString.Create(HttpUtility.HtmlDecode(sysSettings.MaintenanceMessage)) 
+1

雖然需要小心使用,但如果內容是用戶生成的,您將被廣泛開放給XSS攻擊 – mxmissile

+0

非常好。那就是訣竅。在這種情況下,只有最高級別的管理員才能訪問該字段,並且該消息只會顯示在網站的後端。但是,警告指出。謝謝! – jwatts1980

0

,如果你把它發送到視圖它的工作原理之前更換ASCII。我們通過這些發送我們的字符串

public string Decode(string value) 
    { 
     return (value) 
      .Replace("&quot;", "\"") 
      .Replace("&lt;", "<") 
      .Replace("&gt;", ">"); 
    } 

    public string Encode(string value) 
    { 
     return (value) 
      .Replace("\"", "&quot;") 
      .Replace("'", "''") 
      .Replace("<", "&lt;") 
      .Replace(">", "&gt;"); 
    } 
0

檢查您的存儲內容。也許當你試圖將它存儲在數據庫中時,它會用編碼字符替換特殊的HTML字符。例如:

在Unicode格式,從HTML標籤每<標誌將與&#60來代替;字符。

最好存儲原始HTML,然後存儲編碼的HTML,這樣就不必處理編碼/編碼轉換。