bokkie
bokkie

Reputation: 1590

Bind collection to jquery variable from code behind

I have found a great example of a slideshow in jquery, but the image paths are given like this:

  <script type="text/javascript">
        $(function () {
            $('#kenburns').kenburns({
                images: ['http://farm5.static.flickr.com/4088/4967743590_8e1cbba701_b.jpg',  
                         'http://farm5.static.flickr.com/4130/4967739638_edfdb0a52b_b.jpg',  
                         'http://farm5.static.flickr.com/4126/4967708868_5625c200bd_b.jpg'
                        ],
                        frames_per_second: 30,
                        display_time: 7000  
                            ........
                                    });
                      });

    </script>

In the js file it looks like this:

    (function($){

    $.fn.kenburns = function(options) {
        ..................

        var images = [];
        ...................
     }});

So what I want is to give the image source from code behind, in a List<string> or string[] or something similar. The images will be saved on the disk and I will get from the database the paths to them.

Is there a way to do this? or is there a better approach to solve this?

Thanks

Upvotes: 2

Views: 695

Answers (1)

Rawling
Rawling

Reputation: 50154

You can turn a C# string array into a JavaScript array declaration as follows:

string[] myImageUrls = new string[] { "image1.jpg, image2.jpg" };
var serializer = new JavaScriptSerializer();
string myJavaScriptArray = serializer.Serialize(myImageUrls);

This example gives you the string ["image1.jpg","image2.jpg"]

Now, if your first JavaScript block is inline in your ASPX page, you can put this string into a property in your codebehind, e.g.

protected string ImageUrlArray {
    get {
        return new JavaScriptSerializer()
            .Serialize(getImageUrlArrayFromDatabase());
    }
}

and then "include" it in your script block as follows:

<script type="text/javascript">
    $(function () {
        $('#kenburns').kenburns({
            images: <%= ImageUrlArray %>,
            frames_per_second: 30,
            display_time: 7000  
            ........
        });
    });
</script>

<%= ImageUrlArray %> gets replaced with the value of your property, and you end up with the array in place.

Upvotes: 1

Related Questions