Javascript – Pass Html string from view to controller via ajax call

ajaxasp.net-mvccjavascriptjquery

I have a requirement where I need to pass all the HTML of a div tag to the controller.
I am able to get the HTML, but code fails when I am passing HTML via ajax.

Here's my code.

View:

function abc() {

  var html = $("#div").html();

  data = {
    Html: html
  };

  $.ajax({
        url: '@Url.Action("DisplayResult", "Default")', //
        data: data,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function(result) {
          //do something
        });
    },
    error: function(xhr) {
      alert("error");
    }
});
}

My controller Action method:

[HttpPost]
public FileResult DisplayResult(string Html)
{
    return null;
}

I searched online and found a couple of related posts, but those were talking about different solutions like using Html.Beginform() and submit buttons – but none of those solutions suit my need.

Best Answer

You have javascript errors and your call is wrong you will need to stringify the data.    

function abc() {
        var html = $("#div").html();
        var dataToSend = JSON.stringify({ 'Html': html });

        $.ajax({
            url: '/Home/DisplayResult', //
            data: dataToSend,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                //do something
    },
    error: function(xhr) {
        alert("error");
    }
    });
    }


    And I have this in HomeController:

        [HttpPost]
        public FileResult DisplayResult(string Html)
        {
            return null;
        }