开发者

Toggling a graphic using AJAX, MVC and jQuery?

开发者 https://www.devze.com 2023-04-01 03:58 出处:网络
I have an ASP.NET MVC application with a topic page that shows a list of posts. A user can \'subscribe\' to any topic, and I want this to be achieved via clicking on an image, to toggle their subscrip

I have an ASP.NET MVC application with a topic page that shows a list of posts. A user can 'subscribe' to any topic, and I want this to be achieved via clicking on an image, to toggle their subscription on/off. The change in their subscription status needs to be reflected via the change in this image (illuminated image when they're subscribed, greyed out image when they're not).

The image will be rendered via CSS (I'm using a sprites.png file for this and will just specify 'subscrib开发者_运维百科e-on' or 'subscribe-off' as the class name for the anchor/image tag).

My experience with AJAX under MVC is extremely limited, so am hoping that someone can recommend how to best achieve this? I understand the general concept of how it might work (I could use jQuery to bind an ajax call to the click event of the image, which performs the server-side operation, then I essentially want to change the class assigned to that image (to 'subscribe-on' if the user is now subscribed etc.) but I'm not familiar with the underlying code to achieve it.

I would also ideally like to toggle the title text of the anchor tag that wraps the image, so it prompts the user to either 'click to subscribe' or 'click to unsubscribe'.


Like you said, the steps you need are:

  1. Bind to click event on image http://api.jquery.com/click/
  2. Make ajax request to update data on server http://api.jquery.com/jQuery.post/
  3. Handle ajax request on server.
  4. Change class of image in callback function http://api.jquery.com/toggleClass/
  5. Change title of image in callback function http://api.jquery.com/attr/

Example:

$('#subscribeimg').click(function() {
    var that = $(this);
    var id = // get id for topic
    $.post('controller/action', { id: id }, function() {            
         that.toggleClass('subscribe-off subscribe-on');
         that.attr('title', that.hasClass('subscribe-on') ? 'click to unsubscribe' : 'click to subscribe');
    });
});

JS Fiddle Example without Ajax

MVC:

public ActionResult Subscribe(int id) 
{
    // Update database to subscribe/unsubscribe        
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号