2014-09-02 134 views
0

我在MVC4中有一個小應用程序。它有一個網格,每一行都有兩個東西。 1)ID 2)按鈕將參數傳遞給javascript按鈕單擊處理程序

當用戶點擊一個按鈕,我需要調用一個JavaScript函數傳遞ID作爲參數。我怎樣才能在MVC中做到這一點。我可以很輕易地做到這一點。請幫忙

以下是我的代碼。

@model IEnumerable<Models.Asset> 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p> 
    @Html.ActionLink("Create New", "Create") 
</p> 
<table> 
    <tr> 
     <th> 
      Id 
     </th> 

     <th> 
      Show 
     </th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td width="80"> 
      @item.Id 
     </td> 


     <td> 
      <button class="btnView" onclick="myfunction(@item.someProperty)">Show</button> 
     ///How can I pass @item.someProperty as an parameter to click handler? 
     </td>    
    </tr>  
} 
</table> 


<div id="imageDisplay"> 

    <p> 

    </p> 
</div> 

@section scripts{ 
    <script type="text/javascript"> 
     $(function() { 
      $('#imageDisplay').dialog({ 
       autoOpen: false 
      }); 

      $('.btnView').click(function() { 
       alert('ok'); 
       //How can I get id as an parameter to this function? 
      });    

     }); 

    </script> 
} 

回答

3

首先只是從按鍵上移開onclick處理器(如你正在處理click事件與jQuery你並不需要它)

試試這個:

HTML: -

<td> 
    <button class="btnView" data-prop="@item.someProperty">Show</button> 
</td> 

JQUERY: -

$('.btnView').click(function() { 
    var prop = $(this).attr('data-prop'); 
    alert(prop); 
}); 

OR

$('.btnView').click(function() { 
    var prop = $(this).data('prop'); 
    alert(prop); 
}); 

或者(如果你不希望添加按鈕data-prop那麼你可以按照下面的回答,正好趕上'Id'這是那裏tdtable

$('.btnView').click(function() { 
    var id = $(this).closest('tr').find('td').eq(0).text(); 
    alert(id); 
}); 
+0

我會用。數據去(「託」),而不是.attr(「數據道具」)得到它雖然雙方應努力 – Jason 2014-09-02 05:08:58

+0

@ moo2u2。 ..yes..yes你這樣做也...爲你修改答案... – 2014-09-02 05:09:19

0

從按鈕中刪除onclick處理程序(您沒有稱爲myfunction的功能)

由於您已經擁有ËID上一列值,可以使用

$('.btnView').click(function() { 
    var id = $(this).closest('tr').children('td').eq(0).text(); 
}); 
相關問題