2011-09-22 47 views
1

在我的網站,我收集的數字(排序)的列表,並與下面的代碼發送到我的MVC行動:爲什麼我的MVC Action沒有模型綁定我的集合?

$('#saveButton').click(function() { 
     var configId = $('#ConfigId').val(); 
     var steps = new Array(); 
     $('#stepList li').each(function (index) { 
      steps[index] = $(this).attr('stepId'); 
     }); 

     // Send the steps via ajax 
     $.ajax({ 
      url: '" + Url.Action(MVC.GrmDeployment.EditStep.Reorder()) + @"', 
      type: 'POST', 
      dataType: 'json', 
      data: { configId: configId, stepIds: steps }, 
      success: function (data) { 
       if (data.success) { 
        alert('Reorder was successful'); 
       } 

       else { 
        alert(data.msg); 
       } 
      } 
     }); 
    }); 

通過鍍鉻我看到這個發送以下數據通過有線:

configId:1 
stepIds%5B%5D:3 
stepIds%5B%5D:2 

在我的控制,我有以下方法來接收值

public virtual ActionResult Reorder(int configId, ICollection<int> stepIds) { } 

的問題是stepIds集合爲空。任何人看到任何理由爲什麼

+0

我見過各種資源說可以綁定到'IList <>'或'ICollection <>',事實證明我不得不使用特定的jquery選項來使它工作。 – KallDrexx

回答

1

我記得,jQuery的改變它編碼陣列在ajax方法,所以爲了繼續是與MVC兼容的,你必須設置traditional選項true方式:

$.ajax({ 
     url: '@Url.Action(MVC.GrmDeployment.EditStep.Reorder())', 
     type: 'POST', 
     dataType: 'json', 
     traditional: true, // This is required for certain complex objects to work with MVC AJAX. 
     data: { configId: configId, stepIds: steps }, 
     success: function (data) { 
      if (data.success) { 
       alert('Reorder was successful'); 
      } 

      else { 
       alert(data.msg); 
      } 
     } 
    }); 
+0

修復它!謝謝 – KallDrexx

1

使用JSON.Stringify

var viewModel = new Object(); 
viewModel.configId = $('#ConfigId').val(); 
viewModel.steps = new Array(); 

data: { JSON.Stringify(viewModel) }, 
+0

這似乎並沒有工作,它只是抱怨'configId'參數沒有提供,並且需要 – KallDrexx

0

我有行動結合陣列。我個人有一個字符串[]參數的動作。

嘗試

public virtual ActionResult Reorder(int configId, int[] stepIds) { } 
相關問題