0

My controller code:

    public async Task<ActionResult> GetHtml(int id)
    {
        var myModel = await db.Models.FindAsync(id);

        return Json(new { jsonData = myModel.MyHtml }, JsonRequestBehavior.AllowGet); 
    }

My View code:

$('#MyDropDownList').on('change', function() {
    var myModelId = $(this).val();
    var urlGetMyHtml = '@Url.Action("GetHtml", "MyHtmlController")';
    $.getJSON(
        urlGetMyHtml,
        { id: myModelId },
        function(jsonData) {
            console.log(jsonData);                
            $('textarea#MyHtmlArea').val(jsonData);
    });
});

The success function never executes... I checked Fiddler and Firebug, and the code runs successfuly on controller and delivers on client. But then the function is not executed...

Researching, I discovered the success function executes only if we have a valid JSON, then my guess is that my JSON contains HTML code (its for an WYSIWYG editor, like tinymce) getJSON says it is not valid...

So, whats the correct way to send my html snippet using ajax?

3
  • The typical way to do this is have your controller return a view or a partial view instead of json. Commented Jan 3, 2017 at 22:32
  • 1
    well.. HTML isn't JSON. so if you want to return JSON, either format the HTML within a JSON string, or... return HTML instead. Commented Jan 3, 2017 at 22:34
  • Have you tried HttpServerUtility.HtmlEncode ? that would encode any html into safe string. Commented Jan 3, 2017 at 23:07

1 Answer 1

1

To me it seems a little bit far fetched to return HTML as JSON even though it would be possible.

You can simply return Content(myModel.MyHtml) if you want to just return a string of HTML-code.

In your javascript you then need to replace your call to $.getJSON with a simple $.get which like $.getJSON but does not expect JSON-data in the response.

    $.get(urlGetMyHtml,
          { id: myModelId },
          function(response) {
              $('textarea#MyHtmlArea').val(response);
          });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.