khorshid
khorshid

Reputation: 59

How to pass value from table to ajax function in Asp.net

I'm listing all users identity names in my Asp.net MVC

<table class="table table-condensed">
<thead>
    <tr>
        <th>User Name</th>
        <th>Details</th>
    </tr>
</thead>
<tbody>
    @if (Model != null)
        {
            foreach (var item in Model)
            {
            <tr>
                <td>@item.UserName</td>
                <td>   <input type="button" id="show" class="show"  value="Show Roles" /></td>
            </tr>
        }
    }
</tbody>

I want to show user details using ajax when button show been clicked

For this I added div to display data in the same view;

<div id="target">Trigger</div>

and ajax get the details from the action control

<script type="text/javascript">
$(document).ready(function () {
    $('.show').click(function () {

        $.ajax({
            type: 'GET',
            data: { UserName:'xxxxxxx'},
            url: '@Url.Action("DisplyRoles","Admin")',
            success: function (result) {
                $("#target").html(result);

            },
            error: function (error) {
                alert("Error");

            }
        });

    });
  });

My question: What to put instead of xxxxxx as I want to pass current user name which is in the same row of show button?

Upvotes: 0

Views: 1135

Answers (1)

user3559349
user3559349

Reputation:

Add a data- attribute in the <button>. Note also that you should remove the id attribute (duplicate id attributes are invalid html)

<input type="button" data-username="@item.UserName" class="show"  value="Show Roles" />

and then access it in the script

$('.show').click(function () {
    var name = $(this).data('username');
    $.ajax({
        type: 'GET',
        data: { UserName: name },
        url: '@Url.Action("DisplyRoles","Admin")',
        success: function (result) {

You could also access it by reading the value from the previous <td> element

var name = $(this).closest('tr').find('td').eq(0).text();

Upvotes: 2

Related Questions