views:

40

answers:

0

Say, we have a list of songs we want to display. If the user is logged in, he can favorite a song in a list of songs. We want to accomplish this using ajax.

So we have the usual Song repository up, from where we fetch (paginated) songs and push them to view.

In the view, we have something like

<% foreach (Song song in Model) { %>
  ... Display song properties ...
  ... If this already is a favorited song, display image "favorite.png"
  ... Else, display image "notfavorite.png"
<% } %>

Lets say we map favorite songs using a bridge table the following way: Songs <=> FavoriteSongs (has foreign key to songs and users tables) <=> Users

First question: How do we check whether song X is already user's favorite and push this information to the view (for use in the if-else clause above)?

When using ajax and images, we use an extension method ImageActionLink to create an ajax image link with an action.

<div id="favoriteSong">
    <%=Ajax.ImageActionLink("favorite.png", "", "FavoriteSong", new { id = item.SongID }, new AjaxOptions { OnSuccess = "onFavoriteSongComplete" }) %>
</div>

Lets say the server returns whether the song is now a favorite using a boolean on complete. So then we have the JS for onFavoriteSongComplete:

    <script type="text/javascript">
            function onFavoriteSongComplete(context) {
                var json = context.get_data();
                var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
                if (data.IsFavorite)
                    $('#favoriteSong').text(/*Something to change the ImageActionLink's image to favorite.png*/);
                else
                    $('#favoriteSong').text(/*Something to change the ImageActionLink's image to notfavorite.png*/);
            }
    </script>

But since this is a list of songs, every song has now the favoriteSong id. How do we update the correct id (the song user just favorited/unfavorited)? Do we number each id with a number in the loop or can we do this more elegantly somehow by passing the div element to the js or something?

How do we generate the new ImageActionLink, with the proper image, after onFavoriteSongComplete?