2017-02-10 26 views
0

我有我的看法是這樣一個循環,產生student`s名得到錯誤404,同時傳遞一個數組通過Ajax控制器

<Table id="your_table"> 
<thead> 
<tr> 
    <th>name</th> 
    <th>grade</th> 
    <th>remove</th> 
</tr> 
</thead> 
<tbody> 
    @foreach (string item in Model) 
    { 
     <tr> 
      <td id="td_name" style="border-left: thin">@item</td> 
      <td><input type="text" id="[email protected]" onclick="" style="width: 40px;border-left: thin" /></td> 
      <td><input type="checkbox" id="[email protected]" value="@item" /></td> 
     </tr> 

    } 
</tbody> 

我用下面的腳本得到的文本列表每行的第一個單元格:

$('#btnDone') 
      .click(function() { 
     //get studentslist 
     function getFirstCellTextList(tableElement) { 
      if (tableElement instanceof jQuery) { 
       // Create an array 
       var textList = []; 
       // Iterate over each table row 
       tableElement.find('tbody tr').each(function() { 
        // Get the first cells's text and push it inside the array 
        var row = $(this); 
        if (row.children('td').length > 0) { 
         textList.push(row.children('td').eq(0).text()); 
        } 
       }); 
       return textList; 
      } 
      return null; 
     } 
     // Get the array 
     var lststudents = getFirstCellTextList($('#your_table')); 
     var result = []; 
     $(lststudents).each(function(index, item) { 
      result.push(item); 
     }); 

     alert(result); 
     $.ajax('/TeacherPages/GetGrades/' + result).done(function() { 
      alert("done"); 
     }); 
    }); 

問題是。當我想發送創建的數組到控制器我得到錯誤404。這個數組有問題。因爲當我手動添加值到陣列的AJAX工作沒有任何問題

這是我的行動:

[AttributeRouting.Web.Mvc.GET("/TeacherPages/GetGrades/{result}")] 
    public PartialViewResult GetGrades(string[] result) 
    { 
     return PartialView(); 
    } 

enter image description here

+0

不硬編碼的網址,不喜歡:'$阿賈克斯( '@ Url.Action( 「GetGrades」, 「TeacherPages」)'',並顯示你的行動是如何看起來像 –

+0

你?如果你的方法有一個參數IEnumerable name,你的數組看起來像什麼? –

+0

不能只是追加一個JavaScript數組到一個url - 你的url需要看起來像/ TeacherPages/GetGrades?name = ABC&name = DEF&name = etc它就像:name1.lastname1,name2.lastname2 –

回答

1

你不能只追加一個JavaScript數組您的網址。它只是轉換值數組一個逗號分隔字符串中,而你需要生成一個URL是

/TeacherPages/GetGrades?result=someValue&result=anotherValue&result=etc... 

更改你的腳本

$.ajax({ 
    url: '@Url.Action("GetGrades", "TeacherPages")', // don't hardcode your url's 
    type: 'POST', 
    traditional: true, 
    data: { result: result }, 
    success: function (response) { 
     .... 
    } 
}); 

作爲一個側面說明,你getFirstCellTextList()函數返回你想要的數組和它的無意義來創建另一個相同的數組。你只需要

var result = getFirstCellTextList($('#your_table')); 
+0

謝謝。它做到了。但很奇怪。我試圖在幾個不同的場合發送這樣的信息到這個項目中的行動中,沒有任何錯誤。 –

相關問題