如何从Html.ActionLink转换为链接到Ajax调用的按钮

How to convert from Html.ActionLink to a button linked to Ajax call?

本文关键字:Ajax 调用 按钮 链接 Html ActionLink 转换      更新时间:2023-09-26

我有以下代码:

 @Html.ActionLink("Edit", "Edit", new { id = user.Id },
    new { @class = "btn btn-primary btn-xs", @id="edituserbutton"})

我将其转换为按钮的部分尝试如下:

<button class="btn btn-primary btn-xs" id="edituserbutton">
      Edit
</button>

如何将id=user.id从html按钮版本传递给控制器,该控制器的单击事件与Ajax绑定?我的目标是使用Ajax在当前页面中显示编辑屏幕,而不是在单独的页面中导航到编辑页面(ActionLink编辑就是这样(。

$("#edituserbutton").click(function (event) 
{

                event.preventDefault();
               // alert("edit clicked");
                $.ajax({
                    url: "/Admin/Edit",
                    cache: false,
                    data: {}
                }).done(function (htmlResponse) {
                    $("#tabs-1ua").html(htmlResponse);
                });

});

tabs-1ua是我要将编辑页面加载到的jqueryUI选项卡的div。

控制器中编辑方法的签名分别针对GET和POST如下:

 public async Task<ActionResult> Edit(string id)
{
                AppUser user = await UserManager.FindByIdAsync(id);
                if (user != null)
                {
                    return View(user);
                }
                else
                {
                    return RedirectToAction("Index");
                }
 }
[HttpPost]
public async Task<ActionResult> Edit(string id, string email, string password)
{
    //code
}

谢谢。

您可以将id值存储在data-*属性中。类似这样的东西:

<button class="btn btn-primary btn-xs" id="edituserbutton" data-id="@user.Id">
  Edit
</button>

然后在jQuery代码中检索单击按钮的值:

$("#edituserbutton").click(function (event) 
{
    event.preventDefault();
    $.ajax({
        url: "/Admin/Edit",
        cache: false,
        data: { id : $(this).data('id') }
    }).done(function (htmlResponse) {
        $("#tabs-1ua").html(htmlResponse);
    });
});