2010-09-16 63 views
1

當我在頁面中編輯單個記錄時,我使用複選框來獲取選定的行,而不是每行都有一個actionlink元素,但似乎我不能讓這種方式發生通過調用JavaScript代碼(函數GetSelectedRow()應該返回一個id)。任何人都可以有一個好主意嗎?ASP.NET MVC:如何在Html.ActionLink中調用javascript函數

<head runat="server"> 
    <title>Index</title> 
    <script type="text/javascript" language="javascript"> 
     function GetSelectedRow() { 
      var a = 0; 
      var chkBoxes = document.getElementsByName("chkSelect"); 
      var count = chkBoxes.length; 
      for (var i = 0; i < count; i++) { 
       if (chkBoxes[i].checked == true) 
        a = chkBoxes[i].primaryKeyID; 
      } 
      return a; 
     } 
    </script> 
</head> 
<body> 
    <div> 
     <span style="width:20%"> 
     <%: Html.ActionLink("Add", "Create")%> 
     </span> 
     <span> 
     <%: Html.ActionLink("Edit", "Edit", new { id = GetSelectedRow()) %> 
     </span> 
     <span> 
     <%: Html.ActionLink("Detial", "Details", new { id = GetSelectedRow() })%> 
     </span> 
     <span> 
     <%: Html.ActionLink("Delete", "Delete", new { id = GetSelectedRow()) %> 
     </span> 
    </div> 
    <table> 
     <tr> 
      <th></th> 
      <th> 
       CategoryID 
      </th> 
      <th> 
       CategoryName 
      </th> 
      <th> 
       Description 
      </th> 
     </tr> 
     <% foreach (var item in Model) { %> 
      <tr> 
      <td> 
      <%: Html.ActionLink("Details", "Details", new { id = item.AppCategoryID })%> 
      </td> 
       <td> 
        <%: Html.CheckBox("chkSelect", false, new { primaryKeyID = item.AppCategoryID })%> 
       </td> 
       <td> 
        <%: item.AppCategoryID %> 
       </td> 
       <td> 
        <%: item.AppCategoryName %> 
       </td> 
       <td> 
        <%: item.Description %> 
       </td> 
      </tr> 
     <% } %> 
    </table> 
</body> 

回答

0

混合服務器和客戶端的方式將無法正常工作。當你選擇一行時,你需要做的是操縱URL。因此,而不是返回一個URL,有GetSelectedRow做到:

function GetSelectedRow() { 
    //existing logic minus return 

    var link1 = document.getElementById("Link1"); //this would require giving links an ID 
    link1.href = '<%= Url.Action("Detail", new { controller = "Details" }) %>' + 
    'id=' a.toString(); 
} 

你必須從客戶端更改JavaScript是關鍵,而不是這樣做,在渲染過程中。

HTH。

3

你可以做這樣的事情:

<script type="text/javascript"> 
function RedirectUsingSelectedRow() { 
    var id = GetSelectedRow(); 
    window.location = '../Controller/Details/' + id; 
} 
</script> 

<a href="#" onclick = "RedirectUsingSelectedRow();">Edit</a> 
0

試試這個 -

$('#GetSelectedRow').click(function() { /* Your Code */ }); 

通過ID調用Java腳本函數 'GetSelectedRow'。您可以直接調用功能

<% Html.ActionLink("Edit", "Edit", "Controller", new { onclick = "GetSelectedRow();"}) %> 
相關問題