Onclick event for li with javascript in asp.net mvc

北慕城南 提交于 2019-12-02 18:03:25

问题


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


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


来源:https://stackoverflow.com/questions/17501317/onclick-event-for-li-with-javascript-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!