Onclick event for li with javascript in asp.net mv

2019-03-06 11:34发布

<ul>
@foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
{
<li>
@Ajax.ActionLink(item.UserName, "Index", new { item.Id }, new AjaxOptions() { HttpMethod = "Get" });
</li>
}
</ul>

How can ı get item.Id if i onclick item.username with javascript ?

I thought give to attribute to "li onclick".but i dont know there is better solution here or not ?

1条回答
smile是对你的礼貌
2楼-- · 2019-03-06 11:55

You could use a standard link and data-* attribute:

<ul>
    @foreach (var item in Model.Users.Where(s => s.DepartmentId == 3))
    {
        <li>
            @Html.ActionLink(
                item.UserName, 
                "Index", 
                new { id = item.Id },
                new { @class = "myLink", data_id = item.Id }
            )
        </li>
    }
</ul>

and then in a separate javascript file:

$(function() {
    $('.myLink').click(function() {
        // get the id:
        var id = $(this).data('id');
        alert(id);

        // now you can send the AJAX request
        $.get(this.href);

        // cancel the default action of the link
        return false;
    });
});
查看更多
登录 后发表回答