1

I've got an ASP.NET MVC 3 project which works with jQuery. At some point a jQuery $get() call is made to a controller method with a return type of JsonResult. One of the fields is an HTML field.

For some reason it doesn't return the HTML but encodes it.

I've tried HtmlEncode, HtmlDecode, HtmlString etc... - nothing works.

It's always

"\u003cp\u003e" or "&<"

and never gives the real HTML such as

<p>some paragraph</p>

So jQuery will always write down all the tags and not parse them (such as the paragraph which won't be shown as a paragraph but will be written as it is with the HTML tags). No need to say that in the DB I've got the HTML itself with no encoding.

help would be much appreciated :)

Thank

arb
  • 7,753
  • 7
  • 31
  • 66
Roman
  • 4,443
  • 14
  • 56
  • 81

3 Answers3

3

No idea what you are doing wrong since you have shown exactly 0 code.

But the following works perfectly fine for me and no encoding occurs whatsoever:

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult AjaxTest()
    {
        return Json(new { HtmlField = "<p>some paragraph</p>" }, JsonRequestBehavior.AllowGet);
    }
}

View:

<script type="text/javascript">
    $.getJSON('/home/ajaxtest', function (result) {
        $('body').append(result.HtmlField);
    });
</script>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This is exactly what I was doing - and had that problem. don't know why. but the jQuery decoding did the job. – Roman Nov 01 '11 at 19:37
  • @roman, well obviously you were not doing exactly what I have shown here since this works without the need of any encoding tricks. – Darin Dimitrov Nov 01 '11 at 19:49
1

Great Sample Darin Dimitrov. Add AjaxTest() to the home controller and drop

<script type="text/javascript">
$.getJSON('/home/ajaxtest', function (result) {
    $('body').append(result.HtmlField);
});

in the about.cshtml view, run the app and select the about link.

RickAndMSFT
  • 20,912
  • 8
  • 60
  • 78
0

I'm not familiar with ASP.NET, but "&amp;&lt;" looks like you're probably just one step away from decoding it correctly. See How to decode HTML entities using jQuery? for how to get the rest of the way.

Community
  • 1
  • 1
Danica
  • 28,423
  • 6
  • 90
  • 122