Alan Budzinski
Alan Budzinski

Reputation: 809

returning data async after jquery $.ajax post request in asp.net mvc

After $.ajax post request to the controllers action I would like to get info from the server and then update my partial view, for example I have a list rendered in my view I delete an item from the list using the $.ajax post request and then i would like my list to update itself asynchronously.

Here is my function that deletes the item from the list:

 $(".btnDeleteCurrentFavSong").click(function () {

    var songId = $(this).attr('name');

    $.ajax({
        type: 'POST',
        url: "/Home/DeleteCurrentFav/",
        data: { id: songId },
        success: ShowMsg("Song deleted successfully"),
        error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
        dataType: "json"
    });
});

Should I somehow redirect to the action on ajax success that returns the list of songs to the view?

Upvotes: 0

Views: 1482

Answers (3)

Lloyd
Lloyd

Reputation: 8406

if your clicked list item looked like this:

<li name="120">Artist - Title</li>

your javascript could look something like this:

$(".btnDeleteCurrentFavSong").click(function () {

    var songId = $(this).attr('name');

    $.ajax({
        type: 'POST',
        url: "/Home/DeleteCurrentFav/",
        data: { id: songId },
        success: function () {
            ShowMsg("Song deleted successfully");
            $("li[name=" + songId + "]").remove();
        },
        error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
        dataType: "json"
    });
});

Upvotes: 1

maxlego
maxlego

Reputation: 4914

option A

  • return deleted item id from action
  • on success remove deleted item with js

option B

  • return partial view from action
  • on success replace container with rendered html

Upvotes: 0

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

It depends upon the user experience that you wish to give. Convention dictates that a user should be shown the effect of their action. From your example it appears that you are doing this via the ShowMsg function. As to whether you should redirect or not, I'm afraid there's nothing authororative out there, do whatever is consistent across your site and would feel natural to users.

Upvotes: 0

Related Questions