2013-12-09 33 views
0

編寫web api項目和我的方法中的參數之一(這是一個json數組)將進入api null。 jQuery的我正在通話與這個樣子的:web api方法調用中的參數爲空

<script> 
    $(document).ready(function() { 
     $('#btnSubmit').click(function() { 
      var jsRequestAction = { 
       appId: 'appName', 
       custId: 'custId', 
       oprId: 'oprId', 
       businessProcess: 'Requisition', 
       action: 'Approve', 
       actionKeys: [ 
        'blah blah 1', 
        'blah blah 2', 
        'blah blah 3' 
       ]      
      }; 

      $.ajax({ 
       type: "POST", 
       content: "json", 
       url: "http://localhost/api/appName/custId/oprId",      
       contentType: "application/json; charset=utf-8", 
       data: JSON.stringify({ requestAction: jsRequestAction }) 
      }); 
     }); 
    }); 
</script> 

我的Web API方法是這樣的:

public IList<ResponseAction> ActionCounter(string appName, string custCode, string custUserName, RequestAction requestAction) 
    { 
     IList<ResponseAction> actionResponseList = new List<ResponseAction>(); 
     var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString); 
     conn.Open(); 

     try 
     { 
      foreach (string s in requestAction.actionKeys) 
      { 
       var command = new SqlCommand 
       { 
        CommandText = "Sql statement", 
        Connection = conn 
       }; 
       command.ExecuteNonQuery(); 

       var reply = new ResponseAction(); 
       reply.responseActionKey = s; 
       reply.responseMessage = "Success"; 
       actionResponseList.Add(reply); 
      } 
      return actionResponseList; 
     } 
     finally 
     { 
      conn.Close(); 
      conn.Dispose(); 
     } 
    } 

RequestAction型號:

public class RequestAction 
{ 

    public string appId { get; set; } 
    public string custId { get; set; } 
    public string oprId { get; set; } 
    public string businessProcess { get; set; } 
    public string action { get; set; } 
    public string[] actionKeys { get; set; } 
    public string actionKey { get; set; } 
} 

當我調試,我通過該方法,當我到達foreach循環,我得到一個空對象引用。看看我的locals部分,我所有的requestAction屬性都是null。在閱讀了一些相關文章後,我試着用[FromBody]標籤前綴對象來無效。任何幫助,將不勝感激。

回答

1

我找到了我的問題HERE的答案。正是這種改變的事情:

$.ajax({ 
      type: "POST", 
      content: "json", 
      url: "http://localhost/api/appName/custId/oprId",      
      contentType: "application/json; charset=utf-8", 
      data: JSON.stringify({ requestAction: jsRequestAction }) 
     }); 

這樣:

$.ajax({ 
      type: "POST", 
      content: "json", 
      url: "http://localhost/api/appName/custId/oprId",      
      data: jsRequestAction 
     }); 

否則,該數據將不會綁定到我的控制器模型,一切都將被清零了。

0

您需要確保對象服務器端與您正在創建客戶端的對象相匹配,以便請求可以直接序列化到對象中。

所以,你的操作方法如下所示:

public IList<ResponseAction> ActionCounter(RequestAction requestAction) 
{ 
    // Do stuff 
} 

凡RequestAction應符合您所創建的JavaScript對象。

+0

從web api方法中除去了requestAction之外的所有參數,我仍然得到空值。我應該提到,我正在將此方法從我之前構建的WCF休息服務中移除,但我在web api中遇到了這個問題。 –