Javascript jquery Ajax 调用 - 数据参数未传递给 MVC 控制器操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2002163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:20:08  来源:igfitidea点击:

jquery Ajax call - data parameters are not being passed to MVC Controller action

javascriptjqueryasp.net-mvcajax

提问by Grant

I'm passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the client side but the matching parameters on the server side are null.

我将 jQuery ajax 调用中的两个字符串参数传递给 MVC 控制器方法,期望返回 json 响应。我可以看到参数填充在客户端,但服务器端的匹配参数为空。

Here is the javascript:

这是javascript:

$.ajax({  
  type: "POST",  
  contentType: "application/json; charset=utf-8",  
  url: "List/AddItem",  
  data: "{ ListID: '1', ItemName: 'test' }",  
  dataType: "json",  
  success: function(response) { alert("item added"); },  
  error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});

Here is the controller method:

这是控制器方法:

Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
   'code removed for brevity
   'ListID is nothing and ItemName is nothing upon arrival.
   return nothing
End Function

What am I doing wrong?

我究竟做错了什么?

回答by LukLed

I tried:

我试过:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

和 C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentTypeand set datawithout double quotes.

有效。删除contentType和设置data不带双引号。

回答by Mocksy

If you have trouble with caching ajax you can turn it off:

如果您在缓存 ajax 时遇到问题,可以将其关闭:

$.ajaxSetup({cache: false});

回答by Ahmet Onur

You need add -> contentType: "application/json; charset=utf-8",

您需要添加 -> contentType: "application/json; charset=utf-8",

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

回答by Rakesh Haladi

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

回答by BiLaL

In my case, if I remove the the contentType, I get the Internal Server Error.

在我的情况下,如果我删除contentType,我会收到Internal Server Error

This is what I got working after multiple attempts:

这是我多次尝试后得到的结果:

var request =  $.ajax({
    type: 'POST',
    url: '/ControllerName/ActionName' ,
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
    dataType: 'json'
});

request.done(function(msg) {
    alert(msg);
});

request.fail(function (jqXHR, textStatus, errorThrown) {
    alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});

And this is the controller code:

这是控制器代码:

public JsonResult ActionName(int projId, int userId)
{
    var obj = new ClassName();

    var result = obj.MethodName(projId, userId); // variable used for readability
    return Json(result, JsonRequestBehavior.AllowGet);
}

Please note, the case of ASP.NET is little different, we have to apply JSON.stringify()to the data as mentioned in the updateof this answer.

请注意,ASP.NET 的情况略有不同,我们必须应用到此答案更新JSON.stringify()提到的数据。