开发者

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

The Route is:

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

My Controller is:

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


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

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


ASP.NET MVC does not automatically map incoming JSON data into action method parameters.

See the following article for a solution to add that capability:

http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

Also, I think your jQuery call does not actually send JSON although that seems to be what you want it to do. jQuery will not automatically convert the data object to JSON. You need to convert it to JSON yourself with something like json2.js


how did you get that "jquery ... does not pass parameters"? have you tried to sniff the request with firebug?

you're sending data in POST body but trying to access them in regular way (with using action arguments) like GET.
all POST data is in Request.Form or you have to handle it by binding to some custom ViewModel.


Erm, might be wrong but you are passing in the jQuery i, s, b but in the action you have s, i,b .

The order must be correct for jQuery posts.

EDIT

Here 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜