以下是该方案。我想在表单上使用CKEditor作为富文本字段,但无论出于何种原因,我无法将内容从textarea获取到服务器并返回到页面而不会出现编码问题。这是我编写的小样本程序,试图弄清楚发生了什么。首先,我的观点模型:
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编码的(即&lt; p&gt;等......)。这是表格在帖子前的样子:
pre-post http://www.matthewkimber.com/images/so/pre-post.png
以下是“提交”按钮下方div中的结果:
post result http://www.matthewkimber.com/images/so/posted.png
我在Visual Studio中设置了一个断点,它显示为裸角括号(HTML元素上没有编码,只有字符)。
breakpoint results http://www.matthewkimber.com/images/so/dataInsideTheActionMethod.png
当然,这是精简测试。我已经尝试过对它进行编码,在视图和控制器中对它进行解码都无济于事。
答案 0 :(得分:14)
默认情况下,当您使用剃刀时,所有内容都会被编码。我想你正在寻找Raw method。
使用Fiddler或Firebug检查响应也是一个好主意。
答案 1 :(得分:4)
试试这个:
@Html.DisplayTextFor(modelItem => item.Note)
答案 2 :(得分:2)
您也可以使用HtmlString(“”)