为什么我不能在ASP.NET MVC 3中使用HtmlDecode

问题描述 投票:7回答:3

这是场景。我想在表单上使用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编码的(即<p>等...)。这是表格在帖子前的样子:

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

当然,这是精简测试。我试过编码它,在视图和控制器中解码它无济于事。

asp.net-mvc ckeditor
3个回答
14
投票

默认情况下,当您使用剃刀时,所有内容都会被编码。我想你正在寻找Raw method

使用Fiddler或Firebug检查响应也是一个好主意。


4
投票

试试这个:

@Html.DisplayTextFor(modelItem => item.Note)

2
投票

你也可以使用HtmlString(“”)

© www.soinside.com 2019 - 2024. All rights reserved.