【问题标题】:jquery Ajax call - data parameters are not being passed to MVC Controller actionjquery Ajax 调用 - 数据参数未传递给 MVC 控制器操作
【发布时间】:2011-01-01 09:50:39
【问题描述】:

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

这里是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

我做错了什么?

【问题讨论】:

  • 不应该是data: { ListID: '1', ItemName: 'test' }, 吗?没有双引号。
  • LukeLed 是对的:您传递的是字符串而不是对象。去掉双引号就可以了。
  • 感谢您的回复。我尝试删除双引号并得到相同的结果。
  • @Grant:你删除了contentType吗?使用contentType 不起作用。

标签: javascript jquery asp.net-mvc ajax


【解决方案1】:

我试过了:

<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 并设置data 不带双引号。

【讨论】:

  • 感谢您的回复。我尝试了这个并得到了相同的结果。我的 web.config 文件中是否存在未正确设置的内容?
  • @Grant:你删除了contentType吗?使用 contentType 不起作用。
  • 我从 data 参数中删除了 contentType 和双引号。没有运气。
  • LukLed,感谢您的帮助。删除 contentType 就可以了。我第一次在没有 contentType 的情况下尝试这个,我仍然得到空值,但我一定没有刷新所有内容,因为这已经解决了这个问题。为什么会这样呢?我已经看到发布您必须以这种方式设置 contentType 才能使事情正常工作。 (见encosia.com/2008/03/27/…)。
  • 哇。有趣的是,我的值必须被缓存,因为我现在在参数中得到了一个旧值。这一定是为什么我前几次在没有 contentType 的情况下尝试它仍然得到空值的原因。
【解决方案2】:

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

$.ajaxSetup({cache: false});

【讨论】:

  • 我也有同样的问题。为什么要清除缓存?它的作用是什么?&写在哪里,会在$(document).function(){}里面。
  • 如果是asp.net mvc,您可以使用布局页面在javascript的bt中将其关闭,然后所有页面都将关闭其ajax缓存。唯一的问题是我说过它会为所有 ajax 调用关闭它。您通常可以指定是否要缓存单个 ajax 调用。它通常做的是在 ajax 请求 url 的末尾添加一个日期/时间,这样浏览器/服务器就会被愚弄以为每次都是一个新请求
【解决方案3】:

你需要添加 -> 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>

【讨论】:

    【解决方案4】:
      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")
                }
    );
    

    【讨论】:

    • 在控制器中我认为你需要为 ex: function Additem(var itemObject){ } 取单个值,然后在你需要将字符串转换为对象的函数中
    【解决方案5】:

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

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

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

    这是控制器代码:

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

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

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2011-07-25
    • 1970-01-01
    • 2021-07-29
    • 2020-09-17
    相关资源
    最近更新 更多