2011-03-01 65 views
7

這是場景。我希望使用CKEditor作爲表單上的富文本字段,但出於某種原因,我無法從textarea將內容獲取到服務器,並返回到沒有編碼問題的頁面。這裏是我寫的一些小樣本程序,試圖弄清楚發生了什麼。首先,我的視圖模型:爲什麼我不能在ASP.NET MVC中使用HtmlDecode 3

HomeViewModel.cs

namespace CkEditorTest.Models 
{ 
    public class HomeViewModel 
    { 
     [Required] 
     [DataType(DataType.Html)] 
     [Display(Name = "Note")] 
     public string Note { get; set; } 
    } 
} 

現在我的控制器:

HomeController.cs

using System.Web.Mvc; 
using CkEditorTest.Models; 

namespace CkEditorTest.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(new HomeViewModel()); 
     } 

     [HttpPost] 
     [ValidateInput(false)] 
     public ActionResult Index(HomeViewModel model) 
     { 
      return View(model); 
     } 
    } 
} 

最後,我的觀點:

Index.cshtml

@model CkEditorTest.Models.HomeViewModel 
@{ 
    ViewBag.Title = "CKEditor Test"; 
} 
@section head 
{ 
    <script type="text/javascript" src="@Url.Content("~/Scripts/ckeditor/ckeditor.js")"></script> 
    <script type="text/javascript" src="@Url.Content("~/Scripts/ckeditor/adapters/jquery.js")"></script> 

    <script type="text/javascript"> 
     $(document).ready(function() { 
      $("#Note").ckeditor(); 
     }); 
    </script> 
} 

<h2>CKEditor Test</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(m => m.Note)<br /><br /> 
    @Html.TextAreaFor(m => m.Note)<br /> 
    <input type="submit" /> 
} 

@if (!String.IsNullOrEmpty(Model.Note)) 
{ 
<div id="noteText">@Model.Note</div> 
} 

不管我做什麼,我不能在我的視圖中顯示Model.Note屬性爲HTML。當它到達視圖時,它是HTML編碼的(即<p>等)。這裏是形式是什麼樣子崗前:

pre-post http://www.matthewkimber.com/images/so/pre-post.png

這裏是結果是什麼在div下方的「提交」按鈕:

​​

我給自己定Visual Studio中的一個斷點,它顯示爲空心尖括號(不在HTML元素上編碼,只是字符)。

breakpoint results http://www.matthewkimber.com/images/so/dataInsideTheActionMethod.png

此,當然,是剝離下來測試。我試過對它進行編碼,在視圖和控制器中對它進行解碼無濟於事。非常感謝您的幫助!謝謝!

回答

14

默認情況下,所有內容在使用剃鬚刀時都進行了編碼。我想你正在尋找Raw method

使用Fiddler或Firebug檢查響應也是一個好主意。

+0

另見http://davidhayden.com/blog/dave/archive/2010/12/27/HtmlRawRazorViewEngine。 aspx – JTew 2011-03-01 02:05:37

+1

好吧,我會的。謝謝! – Mateo 2011-03-01 02:06:02

+0

不錯的。在方法上不好的名字,找不到。你不認爲尋找「生」 – 2011-05-20 14:55:11

2

您還可以使用HtmlString( 「」)

4

試試這個:

@Html.DisplayTextFor(modelItem => item.Note) 
相關問題