tags:

views:

20

answers:

2

Hi All,

I am playing around with AJAX functionality using ASP.NET MVC. I have created a page with a menu of categories generated from a database which when clicked makes an AJAX request to a Controller and then a Controller returns a PartialView.

<% foreach (var item in Model.Categories)
{ %>
    <li>
        <%= Ajax.ActionLink(item.CategoryName,
                                "Index", "Home",
                                new { id = item.CategoryID },
                                new AjaxOptions { UpdateTargetId = "gallery" })%>
    </li>
<% } %>


[HttpPost]
    public ActionResult Index(int id)
    {

        List<Image> images = imageRepository.getCategoryImages(id).ToList();

        return PartialView("gallery", images);
    }

The gallery div contains a number of images, on first load it has every image which is stored in a database. I have used lightbox a JQuery plugin so when an Thumbnail is click it enlarges and a user can click through the images. When the partial view is returned the lightbox event handler is no longer bound.

$(function () {
        $('#gallery a').lightBox();
    });

Is it possible to somehow trigger a Javascript function to rebind the handler after the M$AJAX request completes?

This is part of a series of projects I intend to undertake to teach myself how to do some cool things with AJAX in ASP.NET MVC. I intend to release the code on my website once complete so others can learn like I have. I tend to find there are so many example with JQuery -> PHP -> MySQL the open source stack. But very little with ASP.NET MVC.

Thanks,

Jon

+1  A: 

One of the AjaxOptions properties is an OnSuccess property that will call some JavaScript code after a successful AJAX request. Set its value to the name of a JavaScript function that then uses jQuery to activate the LightBox script.

new AjaxOptions { UpdateTargetId = "gallery", OnSuccess="ActivateLightBox" })

And some script:

<script ...>
    function ActivateLightBox() {
        $(function () { 
            $('#gallery a').lightBox(); 
        }); 
    }
</script>
Eilon
You're a fountain of knowledge Eilon! Thanks for your help again!
Jonathan Stowell
A: 

You have two options. Either add that javascript to the gallery view, so it gets run when the partial view is loaded or the better solutions is the one that @Eilon just got in there first with.

s1mm0t
I tried including script in the Partial View but it doesn't execute when loaded. I read an article Phil Haack wrote and he says the Framework doesn't execute script when a partial is passed back in an AJAX request. His article said to use JQuery .live() but I couldn't get it working. Eilon's solution works and is very simple.Thanks,Jon
Jonathan Stowell