Reputation: 2957
I have a small application in MVC4. It has a grid and every row has two things. 1) ID 2) Button
When user click on a button I need to invoke a javascript function passing ID as an parameter. How can I do this in MVC. I can eaisly do thin in case of . Please help
Below is my code.
@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>
}
Upvotes: 0
Views: 2961
Reputation: 18873
Firstly just remove onclick
handler from the button(You don't need it as you are handling click
event with jquery)
Try this :
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);
});
OR(if you don't want to add data-prop
on button then you can follow below answer,Just catch 'Id'
which is there in td
of your table
)
$('.btnView').click(function () {
var id = $(this).closest('tr').find('td').eq(0).text();
alert(id);
});
Upvotes: 4
Reputation:
Remove the onclick
handler from the button (you don't have a function called myfunction
)
Since you already have the ID
value in the previous column, you can get it using
$('.btnView').click(function () {
var id = $(this).closest('tr').children('td').eq(0).text();
});
Upvotes: 0