最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass Html string from view to controller via ajax call - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited Sep 6, 2018 at 23:03 user3559349 asked Sep 6, 2018 at 19:46 SriSri 312 silver badges8 bronze badges 5
  • Do you get an error from MVC when you try to run the code? – just.another.programmer Commented Sep 6, 2018 at 19:52
  • my code doesn't hit the controller , javascript fails! – Sri Commented Sep 6, 2018 at 19:53
  • What error do you get from javascript? (You can open the console to view the error message) – just.another.programmer Commented Sep 6, 2018 at 19:55
  • its a 500 internal server error in my console. Breakpoint in my controller is never hit. However, if I dont pass any data in ajax (just pass null) and make the parameter in my controller optional, there's no problem. So, I am assuming something is going wrong when I am passing the html ? – Sri Commented Sep 6, 2018 at 20:00
  • You need to check the text returned along with the 500. It probably says you sent a potentially dangerous request. See this for more info. – just.another.programmer Commented Sep 6, 2018 at 20:04
Add a ment  | 

6 Answers 6

Reset to default 2

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

Sending Html content is not safe so you will get an error. although you can bypass this error, disabling input validation but it's not remended:

[ValidateInput(false)]
public class YouController: Controller{

}

Just before the ajax call

data = {
    Html: encodeURIComponent(html)
};

Then once back at the controller

[HttpPost]
public FileResult DisplayResult(string Html)
{
   Html = HttpUtility.UrlDecode(Html); 
   return null;
}

This took care of the problem for me

maybe the Content type is wrong, but you can check the error from inside a browser (using the Network tab and clicking your request, or even with fiddler)

I can't say much without testing the code, but another option would be to check the responseText of the error function like :

error: function(xhr, status, error) {
  alert(err.responseText);
}

If you define "application/json" in contentType, you must send it after stringify operation.

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

If you don't define "application/json", the default contentType is "application/x-www-form-urlencoded", which you can pass the object to data parameter without JSON.stringify.

Thanks for your responses!

I was able to solve this problem by adding a string property with [AllowHtml] attribute and passing my html via model.

However, since some of the users responded that it's not safe to pass html, I wrote a method in my controller to generate the same html. Thanks for your answers again!

发布评论

评论列表(0)

  1. 暂无评论