2014-07-07 59 views
0

我在$.post()和我的mvc控制器上遇到了一些麻煩。Jquery Ajax和asp.net mvc控制器

我已經嘗試了幾個例子在網絡上和堆棧溢出這樣的:How can I post an array of string to ASP.NET MVC Controller without a form?

但沒有成功。我只是想字符串數組傳遞給我的控制器:

[HttpPost] 
     public HttpResponseMessage Post([FromBody]List<string> idList, string request, bool auto) 
     { 
      LogHelper.Log(Severity.Info, "Just entered in POST api/files"); 

      var fileList = new List<string>(); 

      switch (request) 
      { 
       case "Activate": 
        fileList = auto ? _bendingsServies.GetBendigsToCome() : idList; 
        _filesServices.Activate(fileList); 
        break; 
       case "Archive": 
        fileList = auto ? _filesServices.GetFilesToArchive() : idList; 
        _filesServices.Archive(fileList); 
        break; 
       default: 
        return ControllerContext.Request.CreateResponse(HttpStatusCode.BadRequest); 
        break; 
      } 
      return ControllerContext.Request.CreateResponse(HttpStatusCode.OK); 
     } 

和我的jQuery:

@using System.Configuration 
var api_url = "@ConfigurationManager.AppSettings["apiUrl"]"; 
$(document).ready(function() { 
    // ---- Ajax calls ---- // 
    $("#archivebutton").click(function() { 
     var url = api_url + "Files?request=Archive&auto=false"; 
     var fileList = ["10", "14", "12"]; 
     var postData = { idList: fileList } 
     $.post(url, $.param(postData,true)); 
    }); 
}); 

隨着我什麼都試過,在idList總是包含0的元素,當我嘗試它。

// ---- ----編輯//

我可以,如果我將其封裝在一個JSON對象發送數據:

$("#activatebutton").click(function() { 
       var url = api_url + "Files?request=Activate&auto=false"; 
       var fileList = ["this", "is", "a", "test"]; 
       $.post(url, { fileList: fileList}); 
      }); 

,這是要求: enter image description here

+0

如果直接傳遞fileList而不將其包裝在postData中會發生什麼? $ .post(url,$ .param(fileList,true)); – swestfall

+0

嘗試不指定「傳統」爲「*淺*」集合。只需要'.param(postData)'。 –

+0

不...還是沒有在另一邊。 – AntoineLev

回答

0

其實我的問題不是與ajax,但它的事實是,我的網絡界面正在調用我的API在另一個域上。

你想尋找這一行中的瀏覽器的控制檯進行調試時:

GET http://localhost:49375/a5771720d9814c7faa43fd65fd3aa34d/arterySignalR/negot…9399%2FFile%2FManage&browserName=Chrome&clientProtocol=1.3&_=1404748489560 net::ERR_CONNECTION_REFUSED 

這是如何實現跨域請求: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

感謝大家的幫助!

0

你纏在整個對象,這最終只是發送一個字符串時ModelBinder的就執行,不匹配任何$.param。你應該已經做了:

var postData = { idList: fileList }; 
$.post(url, postData); 

你也應該回調添加到$.post,如果沒有其他原因,而不是一次的過程正確完成,只是通知用戶。

編輯

對不起,我是不是真的想它,但你不應該在所有在這種情況下使用$.param。只需將完整的對象傳遞給$.post即可。

+0

還是什麼都沒有。你可以看到我的編輯 – AntoineLev

+0

我在發佈問題之前嘗試過編輯過的東西。 – AntoineLev

+0

根據我的編輯,我在回答和歪曲之前並沒有完全想到它。你根本不應該使用'$ .param' * *。沒有理由。您是否嘗試過簡單地提交整個對象,因爲我的更正答案表明? –