Ajax call with jQuery in ASP.NET MVC does not pass parameters

Route:

routes.MapRoute(
    "Ajax", // Route name
    "BizTalk/Services/{action}", // URL with parameters
    new
    { // Parameter defaults
     controller = "BizTalk"
    }
   );

My controller:

public JsonResult AjaxTest(string s, int i, bool b)
  {
   return Json("S: " + s + "," + "I: " + i + "," + "B: " + b);
  }

My jQuery code:

$(document).ready(function() {
   $("#btn_test").click(function() {
    var s = "test";
    var i = 8;
    var b = true;
    $.ajax({
     type: "POST", cache: false,
     url: "/BizTalk/Services/AjaxTest",
     data: { i: i, s: s, b: b },
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(msg) {
     }
    });
   });
  });
+3
source share
4 answers

This post explains the problem and a possible solution (similar to what @Erv explained).

If you remove contentType: "application/json; charset=utf-8"from your call before jQuery.ajax, the default content type (form-urlencoded) will be used and the json data that you specified as the data parameter ( data: { i: i, s: s, b: b }) will be correctly mapped to your action parameters .... so if you really don’t want to send json data, just delete the contentType and you'll be fine .....

+7
source
+2

, "jquery... "? firebug?

POST, ( ), GET.
POST Request.Form, , ViewModel.

+1

Erm may be wrong, but you pass jQuery i, s, b, but in the action you have, i, b.

The order must be correct for jQuery posts.

EDIT

This is how I use jQuery posts;

JQuery

        $.post("/Articles/jQueryAddComment", { commentText: commentText, id: id, type: commentType }, function(returnedHTML) {
//Do something with the returned html.
        });

In my controller

        public ActionResult jQueryAddComment(string commentText, int id, string type)
        {
//do some stuff
                return PartialView("CommentList", fvm);
        }
0
source

Source: https://habr.com/ru/post/1744430/


All Articles