1

So I use the TEXTAREA tag to send comment text (1500 characters max) but It doesn't work.

When I use just a couple of words to send then it is working fine.

Any clue, guys?

The error

Failed to load resource: the server responded with a status of 400 (Bad Request) 

JS

var commentText = $("#commentTextArea").val();
        if (commentText.length > 0) {
             var urlGetComments = window.location.protocol + '//' + window.location.host + "/Gadget/PostComment/" + userId  + "/" + commentText;
             $.ajax({
                 type: "POST",
                 url: urlGetComments,
                 data: "",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function (dataComments) {
                     if (dataComments.html != null) {
                         $('#divCommentsData').html(dataComments.html);
                     }
                 }
             }); 
        }

C#

[AcceptVerbs("POST")]
[HttpPost]
[ValidateInput(false)]
public JsonResult PostComment(string userId, string commentText)
{
    try
    {
NoWar
  • 36,338
  • 80
  • 323
  • 498

7 Answers7

4

You are using the URL to pass the information and many servers have limitation for the characters in the URL. Since your action method accepts POST requests, you can include the data in the "data" parameter, rather than append it to the URL.

$.ajax({
    type: "POST",
    url: urlGetComments,
    data: { 'commentText': commentText },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (dataComments) {
        if (dataComments.html != null) {
            $('#divCommentsData').html(dataComments.html);
        }
    }
}); 
Slavo
  • 15,255
  • 11
  • 47
  • 60
  • Perhaps you are right, man. Pls, share the correct code. Thanks! – NoWar Sep 10 '13 at 12:31
  • The code is there. The only difference from yours is on line 4, where you create a new object to pass to the "data" parameter. – Slavo Sep 10 '13 at 12:40
2

You could set the data to be:

data: "{userId:1, commandText:'cmd text'}",

and change the url to be:

var urlGetComments = window.location.protocol + '//' + window.location.host + "/Gadget/PostComment;
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
2

(for comment in question)

First the best way to create the URL is to have a tag input hidden with URL.Action method, like this:

<input type="hidden" id="url-gadget-comment" 
       value="@Url.Action("PostComment", "Gadget")" />

so you can have the script outside of html.

Then use this value and send data by "POST":

var commentText = $("#commentTextArea").val();
if (commentText.length > 0) {

   $.ajax({
      type: "POST",
      url: $('#url-gadget-comment').val(),
      data: { userId: userId, commentText: commentText },
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (dataComments) {
         if (dataComments.html != null) {
            $('#divCommentsData').html(dataComments.html);
         }
      }
    }); 
}
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
2

Just put this before making a call

jQuery.ajaxSettings.traditional = true;
bRaNdOn
  • 1,060
  • 4
  • 17
  • 37
1

Browsers and servers put a limitation on the length of the query string hence the HTTP 400 error. In ASP.Net, it is 2048 by default, set in HttpRuntime section of your web.config, see http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxquerystringlength.aspx

You are using POST the wrong way, passing the data in the url. You should put your data in the data field of your POST request.

You may try :

var commentText = $("#commentTextArea").val();
if (commentText.length > 0) {
     var urlGetComments = window.location.protocol + '//' + window.location.host + "/Gadget/PostComment/";
     $.ajax({
         type: "POST",
         url: urlGetComments,
         data: {"userId": userId, "commentText": commentText},
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (dataComments) {
             if (dataComments.html != null) {
                 $('#divCommentsData').html(dataComments.html);
             }
         }
     }); 
}
jbl
  • 15,179
  • 3
  • 34
  • 101
1

I was having this same error recently. (400 error on post)

I found that the error was because the data portion of my $.Ajax method needed a few more quotes. Here is what worked for me. In the CSHTML page:

            var vals = cells.toString();

            $.ajax({
                type: "POST",
                url: '@Url.Action("TheAction", "theControl")',
                contentType: "application/json; charset=utf-8",
                data: "{'IDS':'" + vals + "'}",
                dataType: "json",
                success: function (response) {

                    var input = "";
                    document.getElementById("SomeItem").innerHTML = input
                },
                failure: function (response) {
                }
            });

And in the Control:

    [HttpPost]
    public JsonResult TheAction(string IDS)
    {
        ASPNETUSER userProfile = db.ASPNETUSERS.Find(User.Identity.GetUserId());

        //Do something super cool with IDS    
        var retval = <do something with ids>;

        return Json(retval , JsonRequestBehavior.AllowGet);
    }

The key for me was all the quotation marks in this portion of ajax so that the value vals is wrapped in single quotes, and IDS is wrapped in single quotes:

    data: "{ 'IDS' : ' " + vals + " '} ",

for me, vals was a string of comma separated IDS which could get too long for a GET function if the user selected all the IDS on the page.

armstb01
  • 623
  • 8
  • 11
0

Thanks to all! But the final solution that is working for me fine is that one.

var commentText = $("#commentTextArea").val();
if (commentText.length > 0) {
var urlGetComments = window.location.protocol + '//' + window.location.host + "/Gadget/PostComment/`
var params = { userId = 1, commentText: commentText };
                 $.ajax({
                     type: "POST",
                     url: urlGetComments,
                     data: JSON.stringify(params),
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function (dataComments) {
                         if (dataComments.html != null) {
                             $('#divCommentsData').html(dataComments.html);
                         }
                     }
                 }); 
            }

It is based on Using jQuery AJAX to POST multiple variables to an ASP .NET MVC Controller

Community
  • 1
  • 1
NoWar
  • 36,338
  • 80
  • 323
  • 498