Asp.net-Mvc

為什麼我不能在 ASP.NET MVC 3 中進行 HtmlDecode

  • February 7, 2019

這是場景。我想將CKEditor用於表單上的富文本欄位,但無論出於何種原因,我都無法將內容從 textarea 獲取到伺服器並返回到頁面而不會出現編碼問題。這是我編寫的小範常式序,試圖弄清楚發生了什麼。首先,我的視圖模型:

HomeViewModel.cs

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

現在我的控制器:

家庭控制器.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);
       }
   }
}

最後,我的觀點:

索引.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> 等…)。這是表單在發布前的樣子:

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

以下是“送出”按鈕下方 div 中的結果:

發布結果 http://www.matthewkimber.com/images/so/posted.png

我在 Visual Studio 中設置了一個斷點,它顯示為裸尖括號(HTML 元素上沒有編碼,只有字元)。

斷點結果 http://www.matthewkimber.com/images/so/dataInsideTheActionMethod.png

當然,這是精簡的測試。我嘗試過對其進行編碼,在視圖和控制器中對其進行解碼,但均無濟於事。

預設情況下,當您使用剃須刀時,所有內容都會被編碼。我認為您正在尋找Raw 方法

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

嘗試這個:

@Html.DisplayTextFor(modelItem =&gt; item.Note)

引用自:https://stackoverflow.com/questions/5149742