在asp.net mvc中使用javascript进行li的onclick事件

时间:2013-07-06 08:52:51

标签: onclick html-lists

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

如果我用javascript点击item.username,我怎么能得到item.Id?

我认为将属性赋予“li onclick”。但我不知道这里有更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以使用标准链接和data- *属性:

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

然后在单独的javascript文件中:

$(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;
    });
});
相关问题