2017-02-23 119 views
0

我有一個JavaScript函數,我傳遞了4個數組,其中每個數組都是 [1,2],只有int值或者[]裏面沒有值。這些被傳遞給Url.Action命令。傳遞int數組到MVC控制器

function Filter(locations, machines, severities, messages) { 
    var url = '@Url.Action("Filter", "ActiveMessages")?' + $.param({ 
     locations: locations, machines: machines, severities: severities, messages: messages }); 
    $.ajax({ 
     url: url, 
     method: 'POST', 
     traditional: true, 
     success: function (data) { } 
    }); 
} 

我試着用$.param()來構建參數。但是這並不能產生我期待的參數,我得到的是這樣的:"/ActiveMessages/Filter?locations%5B%5D=1"

我也試着這樣做:

decodeURIComponent($.param({ locations: filterlocations, machines: filtermachines, severities: filterseverities, messages: filtermessages })) 

然後我得到的是這樣的: "/ActiveMessages/Filter?locations[]=1&locations[]=2"

有沒有其他方法可以將這樣一個數組解析爲一個url?

接收發生在控制器:

public async Task<ActionResult> Filter(int[] locations, int[] machines, int[] severities, int[] messages) 
{ 
    //TODO filter 
} 

調用此方法,但參數爲null;

當我開始使用這個工作的單個值,但需要擴展到一個數組。

var url = '@Url.Action("Filter", "ActiveMessages")' + '?locations=' + locations + '&machines=' + machines + '&severities=' + severities + '&messages=' + messages; 
+0

你爲什麼要通過URL傳遞它們? –

+0

你會推薦什麼其他方式?我認爲這將是最簡單的方式,因爲數據不是私人的 –

+2

我建議將它們傳遞給AJAX POST,並在數據屬性中包含所有數組。像這樣的東西http://stackoverflow.com/a/5489534/6157222 –

回答

1
一個職位的行動

最佳實踐將是用身體來發送參數後(注paramters的[FromBody]註釋):

[HttpPost] 
public async Task<ActionResult> Filter([FromBody] int[] locations, [FromBody] int[] machines, [FromBody] int[] severities, [FromBody] int[] messages) 

的參數需要在被指定Ajax調用的身體:

function Filter(locations, machines, severities, messages) { 
    var url = '@Url.Action("Filter", "ActiveMessages")'; 
    $.ajax({ 
      url: url, 
      method: 'POST', 
      data: JSON.stringify({ locations: locations, machines: machines, severities: severities, messages: messages }), 
      traditional: true, 
      success: function (data) { 
    }}); 
} 
+0

'[FromBody]'在這裏是不必要的。該方法只允許POST,所以這個數據當然會來自post主體 –

+0

我已經實現了這個,但我仍然在我的控制器中得到空值 –

+0

我已經構建瞭如下數據:data:{'locations':locations,'machines ':machines,'severities':嚴重性,'messages':messages}如 - Ivan Franco所建議的那樣。現在我在控制器中獲取數據 –

1
var locations = [1,2]; 
var machines = [3,4]; 
var severities = [5,6]; 
var messages = [7,8]; 

$.ajax({ 
    url: @Url.Action("Filter", "ActiveMessages"), 
    method: 'POST', 
    data: { 
      locations: locations, 
      machines: machines, 
      severities: severities, 
      messages: messages 
    }, 
    success: function (data) { 
    } 
}); 

在這種情況下,沒有必要字符串化:)

相關問題