简体   繁体   中英

MVC5 controller not receiving html content posted by ajax

Check the JQuery and MVC5 controller code bellow. The problem is that when I post any HTML content from the ajax controller Request.Form["des"] not grabbing the HTML contents but, if I post normal text then it is receiving nicely. Now the question is, what's wrong with the HTML content? I also disabled input security on the controller as you can see in the controller code but still, it is failing to get HTML. Please note my goal is to get the HTML content as a string which posted from ajax. Thanks in advance

Jquery:

//var des = "test"; //this one receiving in controller successfully
var des = "<b>test</b>"; //this one not receiving in controller
var form_data = new FormData();
form_data.append('des', des);
$.ajax({
   url: '/item/dosomething',
   dataType: 'text',
   cache: false,
   contentType: false,
   processData: false,
   data: form_data,
   type: 'post',
   success: function (response) {
     console.log(response);
   },
   error: function (response) {
     console.log(response);
   }
});

MVC5 Controller:

[ValidateInput(false)]
[HttpPost]
public ActionResult DoSomething()
{
  string des = Request.Form["des"];
  return Json("ok");
}

Use [AllowHtml] For HTML Specific Content

If you want to pass HTML to the server, you should consider using the [AllowHtml] attribute to decorate a property (and avoid disabling input validation via the [ValidateInput(false)] attribute):

public class HtmlContent 
{
    [AllowHtml] 
    public string des { get; set; }
}

And then use that class as what you expect to receive in the Controller Action:

[HttpPost]
public ActionResult DoSomething(HtmlContent content) 
{ 
     // Access your element here
     var html = content.des;

     return JsonResult("ok");
}

Consider Just Posting a String

Additionally, since you aren't doing anything overly complex, you could likely consider simplifying your existing AJAX call to leverage the short-hand $.post() as seen below:

var des = '<b>test</b>';
$.post('/item/dosomething', { des: des }, function(response) { console.log(response); });

... Unless You Need a Form

If you absolutely need to post a form (eg use FormData ), you'll likely want to adjust your call accordingly. It's worth noting that you can still bind to the same class defined above (and add additional properties as needed):

var form_data = new FormData();
form_data.append('des', des)

$.ajax({
     url: '/item/dosomething',
     data: form_data,
     processData: false,
     contentType: false,
     type: 'POST',
     success: function(response){
        console.log(response);
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM