0

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>
}

2 Answers 2

4

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'd go with .data('prop') instead of .attr('data-prop') though both should work
0

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.