jQuery的Ajax调用 - 数据参数不被传递到MVC控制器行动 [英] jquery Ajax call - data parameters are not being passed to MVC Controller action

查看:203
本文介绍了jQuery的Ajax调用 - 数据参数不被传递到MVC控制器行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递了两个字符串参数从一个jQuery Ajax调用的MVC控制器的方法,期待一个JSON响应返回。我可以看到参数填充在客户端,但在服务器端的匹配参数为null。

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.

下面是JavaScript:

Here is the 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); }
});

下面是控制器的方法:

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?

推荐答案

我想:

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

和C#:

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

它的工作。删除的contentType ,并设置数据没有双引号。

It worked. Remove contentType and set data without double quotes.

这篇关于jQuery的Ajax调用 - 数据参数不被传递到MVC控制器行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆