簡體   English   中英

jquery Ajax調用 - 數據參數未傳遞給MVC Controller操作

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

我將兩個字符串參數從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

我究竟做錯了什么?

我試過了:

<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而不使用雙引號。

如果您在緩存ajax時遇到問題,可以將其關閉:

$.ajaxSetup({cache: false});

你需要添加 - > 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>
  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")
            }
);

在我的情況下,如果我刪除contentType ,我得到內部服務器錯誤

這是我多次嘗試后的工作:

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()應用於此答案更新中提到的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM