2010-11-10 39 views
1

我是Jquery和Asp.Net MVC的新手。 我想從一個頁面上的ActionLink傳遞一個ID參數什麼是使用asp.net從URL獲取Id的最佳方式mvc

到jQuery函數。 然後將此Id傳遞給控制器​​,該控制器返回在模態對話框中呈現的結果集。

從JQuery中的ActionLink獲取Id參數的最佳方法是什麼? 請注意,有幾個操作鏈接分配有不同的ID。

這是我下面的操作鏈接:

<%=Html.ActionLink("View", "GetDetailsById", new { id = x.ProductId }, new { @class = "view",@productId= x.ProductId })%>

下面這是我的jQuery函數。

 $(function() { 
      var _id; 


      $(".view").click(function() { 
       // Get the ID value of this button. 

       _id = $(this).attr('productId');      

       // Initialize the dialog and call the next function 
       // to get the data.     
       $("#dialog-message").dialog('open'); 

       return false; 
      }); 

請注意,我通過向actionlink添加自定義屬性來獲得此功能 - @ productId。然後我使用jQuery這樣搶值:

$(".view").click(function() { // Get the ID value of this button.

    _id = $(this).attr('productId');    

這個ID被傳遞到調用控制器的方法的jQuery函數。

這是一個獲得Id的好方法,還是有一個更清潔的方式來做到這一點?

問候

科喬

+0

好奇,但它看起來像你正在創建一個行動鏈接,但實際上並沒有使用鏈接本身。但是,請點擊返回false並執行其他操作。我對麼? – 2010-11-10 01:19:59

+0

我正在用CSS類和Id裝飾動作鏈接。我沒有顯示所有的代碼,但我打開了一個模態對話框。 – Kojof 2010-11-10 23:35:07

回答

0

你可以產品ID分配給產生,由HTML指定id的HTML元素的ID屬性參數:

new { @class = "view", id = x.ProductId } 

然後,而不是使用一個productId屬性,您可以用相同的方式獲取生成的<a>標籤的id,即使用$(this).attr("id")

我會推薦使用productId,因爲id是有效的HTML。

所以,你的代碼最終會這樣看:

<%=Html.ActionLink("View", "GetDetailsById", new { id = x.ProductId }, new { @class = "view", id = x.ProductId })%> 

這將產生與productId ID的<a>。然後你的jQuery應該是這樣的:

 $(function() { 
     var _id; 


     $(".view").click(function() { 
      // Get the ID value of this button. 

      _id = $(this).attr('id');      

      // Initialize the dialog and call the next function 
      // to get the data.     
      $("#dialog-message").dialog('open'); 

      return false; 
     }); 
+0

..我用$(this)。attr('id')但它返回undefined,任何想法plz?我只想在上面的actionlink獲取id值在jquery點擊事件 – Dragon 2015-11-04 09:28:37

0

我會通過ID向視圖模型,然後在JavaScript變量插入值手動

<script type="text/javascript"> 
    var id = '<% ViewData["theid"] %>'; 
</script> 

這是相同的技術,計算器在他們的代碼使用。繼續看看他們的html,你會看到。

+0

這是一個有用的技術,並會工作。我不接受它的唯一原因是因爲我有一個List 收集的數據顯示在頁面上的一個表格中。所以我不能在頁面上顯示它之前將單個ID分配給<%ViewData [「theid」]%>。 – Kojof 2010-11-10 22:56:50

相關問題