ITWorker ITWorker - 4 months ago 29
Ajax Question

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

I have the following code:

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


And my partial attempt to convert it to a button is as follows:

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


How can I pass the id=user.id to the controller from the html button version, whose click event is tied to an Ajax? My goal is to bring up the edit screen in the current page, using Ajax, instead of navigating away to the edit page in a separate page (which is what happens in the ActionLink edit).

$("#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
is the div for the jqueryUI tab I want to load the edit page into.

The signatures for the edit methods in the controller are as follows for the GET and POST respectively:

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
}


Thank you.

Answer

You can store the id value in a data-* attribute. Something like this:

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

Then in the jQuery code retrieve the value of the clicked button:

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

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