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

浪尽此生 提交于 2019-12-23 20:42:35

问题


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

回答1:


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.....




回答2:


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




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/2785648/ajax-call-with-jquery-in-asp-net-mvc-does-not-pass-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!