7

Here is the scenario. I want to use CKEditor for a rich text field on a form, but for whatever reason I cannot get the contents from the textarea to the server and back to the page without encoding problems. Here is the little sample program I wrote up to try and figure out what is going on. First, my view model:

HomeViewModel.cs

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

Now my controller:

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); } } } 

And finally, my view:

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> } 

No matter what I do, I cannot display the Model.Note property as html on my view. By the time it reaches the view it is HTML encoded (i.e. <p> etc...). Here is what the form looks like pre-post:

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

And here is what the result is in the div below the "Submit" button:

post result http://www.matthewkimber.com/images/so/posted.png

I've set a breakpoint within Visual Studio and it shows as bare angle brackets (no encoding on HTML elements, just characters).

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

This, of course, is the stripped down test. I've tried encoding it, decoding it both in the view and in the controller to no avail.

3 Answers 3

14

By default everything is encoded when you use razor. I think you're looking for the Raw method.

It would also be a good idea to check the response using Fiddler or Firebug.

Sign up to request clarification or add additional context in comments.

2 Comments

Good one. Bad name on the method tho, har to find. You don't think to look for "raw"
4

Try this:

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

Comments

2

You can also use HtmlString("")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.