2012-11-29 49 views
1

如何使用jQuery Ajax發佈數據元素到控制器操作。使用ajax post發佈數組到MVC3控制器

這是我如何嘗試,但我的控制器收到一個空數組。

function dipatchAllocations() { 
      // unSelected is an array of items of type int. 
      if (unSelected.length == 0) { 
       alert("Please select a line item to be dispatched."); 
       return; 
      } 
      debugger; 
      $.ajax({ 
       type: 'POST', 
       url: '/Batch/SetToDispatch', 
       data: '{ "allocationId[]" : "[' + unSelected + ']","batchId" : "' + @Model.Id + '" }', 
       contentType: "application/json; charset=utf-8", 
       traditional: true, 
       success: updateView, 
       error: errorInSubscribing 
      }); 
     }; 

這是我的控制器

[HttpPost] 
public ActionResult SetToDispatch(long[] allocationId,long batchId) 
{ 
    // Perform some action here 
    return View("_ReadyToDispatchItems",model); 
} 

有人能不能指點我,我錯過了什麼。

感謝

+0

有你累刪除 「[]」 allocationId – ankur

+0

後才能顯示'unSelected'聲明? – testCoder

回答

0

你可以簡單地給控制器作爲查詢字符串數據它會工作

$.ajax({ 
      type: 'POST', 
      url: '/Batch/SetToDispatch/' + unSelected + ',' + batchId 
      dataType: 'json', 
      contentType: "application/json; charset=utf-8", 
      traditional: true, 
      success: updateView, 
      error: errorInSubscribing 
     }); 

它的逗號分隔您可以將其拆分到控制器中並使用它。 希望它可以幫助

1

試試這個:

var data = { allocationId : unSelected, batchId : @Model.Id }; 
$.ajax({ 
       type: 'POST', 
       url: '/Batch/SetToDispatch', 
       data: JSON.stringify(data), 
       contentType: "application/json; charset=utf-8", 
       traditional: true, 
       success: updateView, 
       error: errorInSubscribing 
      }); 
相關問題