0

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?

1 Answer 1

2

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

4 Comments

Yes exactly, it's work perfect. I prefer data- attribute . it's very logically. Thanks a lot!
It's possible to use data-userID or data-anyName rather than data-username ?
Yes, you can use whatever you want
But note it should always be lower case (as defined by the standards)

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.