Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Tuesday, 15 October 2013

Tutorial 6: Create Back To Top hyperlink with animation effect in ASP.NET using jQuery

4 comments
In my previous article, I've explained how to get selected text and value of ASP.NET DropDownList using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to create Back To Top hyperlink with animation effect in ASP.NET using jQuery. In real world web applications, a web page can be longer than the browser window size therefore user have to scroll down in order to see all contents of web page. Back To Top link will be very useful if user want to get back to the top of the page after seeing all the contents.
  • Create a new web form Example1.aspx in ASP.NET web application. Add one div area
    with some dummy text content in the web form. Also add hyperlink below div area.
    <div id="Area1">
                <h1>Scroll down and click on Back To Top</h1>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.
                <br />
                <br />
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.
                <br />
                <br />
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.
                <br />
                <br />
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.                      
            </div>
    <a id="BackToTop" href="#top"><strong><span class="auto-style1">Back To Top</span></strong></a>
  • Define the css style for the hyperlink as below:
    <style type="text/css">
            .auto-style1 {
                color: #0000CC;
                font-size: x-large;
                cursor:hand;
            }
      </style>
  • Write below jQuery code for animation effect.
    <script type="text/javascript">
            $(function () {
                $("#BackToTop").click(function () {
                    $('html,body').animate({ scrollTop: $("#Area1").offset().top },
                    { duration: 'normal', easing: 'swing' });
                    return false;
                });
            });
    </script>
  • In the jQuery code, we are selecting hyperlink BackToTop and animating it using jQuery. Inside animate() function we've used scrollTop and then $("Area1").offset().top as the position that our function scrolls to. We can replace $("Area1") with any element of your choice. We have set the speed duration to "normal". You can also use the keywords fast and slow or set the time in milliseconds for duration. We've add easing effect by easing: 'swing'. Instead of swing, we can also use linear for easing effect. We can also add different easing effects by including the jQuery UI. You can read more about easing effects here. In the end of the code we are returning false, which prevents our link from going to its target: #top.
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding!
Read More...

Sunday, 13 October 2013

Tutorial 5: Getting selected text and value of ASP.NET DropDownList using jQuery

6 comments
In my previous article, I've explained how to Select Deselect all CheckBoxes of ASP.NET CheckBoxList using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to get selected text and value of ASP.NET DropDownList using jQuery.
  • Create a new web form Example1.aspx in ASP.NET project and add one ASP.NET DropDownList. Also add a div tag to display selected text and value of the ASP.NET DropDownList in runtime.
     <asp:DropDownList ID="ddlCountry" runat="server">
                    <asp:ListItem Value="">Select Country</asp:ListItem>
                    <asp:ListItem Value="1">India</asp:ListItem>
                    <asp:ListItem Value="2">England</asp:ListItem>
                    <asp:ListItem Value="3">USA</asp:ListItem>
                    <asp:ListItem Value="4">France</asp:ListItem>
    </asp:DropDownList>
    <div id="ddl"></div>
    
  •  Create a empty string variable.
     var ddltext = "";
    
  • In the document.ready() function in the jQuery script block, use bind() to attach
    a handler to the keyup and change events.
     $("#<%=ddlCountry.ClientID%>").bind("keyup change", function () {
  •  Check whether the selected value of the DropDownList is empty or not. If selected value is not empty then retrieve the Text/Value pair and display in the div tag (ddl) area else clear the div area. 
    $("#<%=ddlCountry.ClientID%>").bind("keyup change", function () {
                    if ($(this).val() != "") {
                        ddltext = "Country Text : " + $(this).find(":selected").text() + " Country Value : " + $(this).val();
                        $("#ddl").text(ddltext);
                    }
                    else {
                        $("#ddl").text("");
                    }
                });
    

Complete Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            var ddltext = "";
            $("#<%=ddlCountry.ClientID%>").bind("keyup change", function () {
                if ($(this).val() != "") {
                    ddltext = "Country Text : " + $(this).find(":selected").text() + " Country Value : " + $(this).val();
                    $("#ddl").text(ddltext);
                }
                else {
                    $("#ddl").text("");
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Please select country:</h3>
            <asp:DropDownList ID="ddlCountry" runat="server">
                <asp:ListItem Value="">Select Country</asp:ListItem>
                <asp:ListItem Value="1">India</asp:ListItem>
                <asp:ListItem Value="2">England</asp:ListItem>
                <asp:ListItem Value="3">USA</asp:ListItem>
                <asp:ListItem Value="4">France</asp:ListItem>
            </asp:DropDownList>
        </div>
        <br />
        <div id="ddl"></div>
    </form>
</body>
</html>
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding! 
Read More...

Saturday, 12 October 2013

Tutorial 4: Select Deselect all CheckBoxes of ASP.NET CheckBoxList using jQuery

1 comment
In my previous article, I've explained how to display selected items of ASP.NET CheckBoxList using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to Select Deselect or Check Uncheck all CheckBoxes of ASP.NET CheckBoxList using jQuery. I'll be using one additional CheckBox control to perform this functionality. This additional CheckBox will be used to Select Deselect all CheckBoxes of ASP.NET CheckBoxList.
  • Create a new web form Example1.aspx in ASP.NET project and add one ASP.NET CheckBoxList (chkboxList) and one CheckBox (chkboxSelectAll) control.
  • <asp:CheckBox ID="chkboxSelectAll" runat="server" Text="Select All" />
                <asp:CheckBoxList ID="chkboxList" runat="server">
                    <asp:ListItem>News</asp:ListItem>
                    <asp:ListItem>Offers</asp:ListItem>
                    <asp:ListItem>Products</asp:ListItem>
                    <asp:ListItem>Advertisement</asp:ListItem>
    </asp:CheckBoxList>
    
  • Write below jQuery code to Check Uncheck all CheckBoxes of ASP.NET CheckBoxList chkboxList on CheckBox (chkboxSelectAll) click event.
    $("#<%=chkboxSelectAll.ClientID%>").click(function () {
                    if ($(this).is(":checked")) {
                        $("#<%=chkboxList.ClientID%> input[type=checkbox]").attr("checked", "checked");
                    }
                    else {
                        $("#<%=chkboxList.ClientID%> input[type=checkbox]").removeAttr("checked");
                    }
                });
    
  • In above code, if  CheckBox chkboxSelectAll is check then I am adding check attribute to all CheckBox of CheckBoxList chkboxList else remove check attribute for CheckBox of CheckBoxList chkboxList. 
  • Whenever any CheckBox of CheckBoxList chkboxList is getting clicked then we have to also verify all CheckBox of CheckBoxList chkboxList. If all CheckBox of CheckBoxList chkboxList are checked then we have to add check attribute to CheckBox chkboxSelectAll else we have to remove check attribute for CheckBox chkboxSelectAll.
    $("#<%=chkboxList.ClientID%>").click(function () {
                    if ($("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").length == $("#<%=chkboxList.ClientID%> input").length) {
                        $("#<%=chkboxSelectAll.ClientID%>").attr("checked", "checked");
                    } else {
                        $("#<%=chkboxSelectAll.ClientID%>").removeAttr("checked");
                    }
    });

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%=chkboxSelectAll.ClientID%>").click(function () {
                if ($(this).is(":checked")) {
                    $("#<%=chkboxList.ClientID%> input[type=checkbox]").attr("checked", "checked");
                }
                else {
                    $("#<%=chkboxList.ClientID%> input[type=checkbox]").removeAttr("checked");
                }
            });

            $("#<%=chkboxList.ClientID%>").click(function () {
                if ($("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").length == $("#<%=chkboxList.ClientID%> input").length) {
                    $("#<%=chkboxSelectAll.ClientID%>").attr("checked", "checked");
                } else {
                    $("#<%=chkboxSelectAll.ClientID%>").removeAttr("checked");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Please choose type of subscription letters:</h3>
            <asp:CheckBox ID="chkboxSelectAll" runat="server" Text="Select All" />
            <asp:CheckBoxList ID="chkboxList" runat="server">
                <asp:ListItem>News</asp:ListItem>
                <asp:ListItem>Offers</asp:ListItem>
                <asp:ListItem>Products</asp:ListItem>
                <asp:ListItem>Advertisement</asp:ListItem>
            </asp:CheckBoxList>
        </div>
    </form>
</body>
</html>
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding! 
Read More...

Friday, 11 October 2013

Tutorial 3: Display selected items of ASP.NET CheckBoxList using jQuery

6 comments
In my previous article, I've explained how to disable CUT, COPY and PASTE options for TextBox using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to display selected items of ASP.NET CheckBoxList using jQuery.
  • Create a new web form Example1.aspx in ASP.NET project and add one ASP.NET CheckBoxList. Also add a div tag to display selected items of the ASP.NET CheckBoxList in runtime.
    <asp:checkboxlist id="chkboxList" runat="server">
                <asp:listitem>News</asp:listitem>
                <asp:listitem>Offers</asp:listitem>
                <asp:listitem>Products</asp:listitem>
                <asp:listitem>Advertisement</asp:listitem>
    </asp:checkboxlist>
    <div id="SelectedItems"></div>
    
  • In the document.ready() event, define the click() function of CheckBoxList.
     $("#<%=chkboxList.ClientID%>").click(function () {
    
  • Create a empty string variable.
     var strSelectedItems = "";
    
  • Use jQuery selector to retrieve all the checked boxes and apply the each() function to
    loop through each element returned.
    $("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").each(function () {
    
    Please note that at run time ASP.NET CheckBoxList will render as table <table id="chkboxList"> and all CheckBox items will render as a <input type="checkbox"> and <label> pair format.
    <table id="chkboxList">
     <tr>
      <td><input id="chkboxList_0" type="checkbox" name="chkboxList$0" value="News" /><label for="chkboxList_0">News</label></td>
     </tr><tr>
      <td><input id="chkboxList_1" type="checkbox" name="chkboxList$1" value="Offers" /><label for="chkboxList_1">Offers</label></td>
     </tr><tr>
      <td><input id="chkboxList_2" type="checkbox" name="chkboxList$2" value="Products" /><label for="chkboxList_2">Products</label></td>
     </tr><tr>
      <td><input id="chkboxList_3" type="checkbox" name="chkboxList$3" value="Advertisement" /><label for="chkboxList_3">Advertisement</label></td>
     </tr>
    </table>
    
  • Get the text of selected CheckBox and append to the string variable strSelectedItems
     strSelectedItems = strSelectedItems + " " + $(this).next().text();         
    
  • As mentioned above, each CheckBox item will render as a <input type="checkbox"> and <label> pair format. The label holds the text of the CheckBox element. Therefore in above code, while retrieving the text of the CheckBox element , we have used $(this).next().text(), where $(this) refers to the current CheckBox element and next() refers to the consecutive <label> element.
  • Display value of string variable strSelectedItems in div after the execution of each() function. 
  •  $("#SelectedItems").text(strSelectedItems);
    

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Display selected items of ASP.NET CheckBoxList using jQuery</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%=chkboxList.ClientID%>").click(function () {
                var strSelectedItems = "";
                $("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").each(function () {
                    strSelectedItems = strSelectedItems + " " + $(this).next().text();                    
                });
                $("#SelectedItems").text(strSelectedItems);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Please choose type of subscription letters:</h3>
            <asp:CheckBoxList ID="chkboxList" runat="server">
                <asp:ListItem>News</asp:ListItem>
                <asp:ListItem>Offers</asp:ListItem>
                <asp:ListItem>Products</asp:ListItem>
                <asp:ListItem>Advertisement</asp:ListItem>
            </asp:CheckBoxList>
            <div id="SelectedItems">          
            </div>
        </div>
    </form>
</body>
</html>

Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding! 
Read More...

Tuesday, 8 October 2013

Tutorial 2: Disable CUT, COPY and PASTE options for TextBox using jQuery

3 comments
In my previous article, I've explained how to create default text or Watermark text for empty TextBox in ASP.NET using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to disable CUT, COPY and PASTE functionality for TextBox using jQuery in ASP.NET applications. Sometimes we want to restrict users to perform CUT, COPY and PASTE operations in few scenarios like confirming email address or confirming password or requesting sensitive information.

Create a new web form Example1.aspx in ASP.NET web application. Create two TextBox : txtEmail and txtEmailConfirm.
 <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
 <asp:TextBox ID="txtEmailConfirm" runat="server"></asp:TextBox> 
  • In the document.ready() event, use bind to attach the required event handler for cut, copy, and paste events for txtEmail TextBox.
     $("#<%=txtEmail.ClientID%>").bind('cut copy paste', function (e) {
    
  • Override the default cut, copy, paste behavior of event and display alert box.
     e.preventDefault();
     alert("Cut Copy Paste is disabled for this textbox");
    
  • Repeat above steps for txtEmailConfirm TextBox.
     $("#<%=txtEmailConfirm.ClientID%>").bind('cut copy paste', function (e) {
                    e.preventDefault();
                    alert("Cut Copy Paste is disabled for this textbox");
                });

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Tutorial 2: Disable Cut Copy Paste for Textbox using jQuery</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%=txtEmail.ClientID%>").bind('cut copy paste', function (e) {
                e.preventDefault();
                alert("Cut Copy Paste is disabled for this textbox");
            });
            $("#<%=txtEmailConfirm.ClientID%>").bind('cut copy paste', function (e) {
                e.preventDefault();
                alert("Cut Copy Paste is disabled for this textbox");
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Confirm Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmailConfirm" runat="server"></asp:TextBox></td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
In above jQuery code, I've repeated same logic for second TextBox txtEmailConfirm. What if we have to do same task for multiple TextBoxes? We'll be ending up by repeating same logic for every TextBox. This task can be minimized by adding a common CSS Class (like class="txtdisable") to the TextBox controls on which we want to disable CUT, COPY and PASTE options and then using jQuery to disable controls having common specific CSS Class. See below source code for reference:
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Tutorial 2: Disable Cut Copy Paste for Textbox using jQuery</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".txtdisable").bind('cut copy paste', function (e) {
                e.preventDefault();
                alert("Cut Copy Paste is disabled for this textbox");
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Name</td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Enter Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server" CssClass="txtdisable"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Confirm Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmailConfirm" runat="server" CssClass="txtdisable"></asp:TextBox>
                    </td>
                </tr>

            </table>
        </div>
    </form>
</body>
</html>


Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding!
Read More...

Tutorial 1: Creating default text or Watermark text for empty TextBox in ASP.NET using jQuery

4 comments
In my previous article, I’ve given beginner’s introduction on how to use jQuery with ASP.NET applications. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to create a TextBox in ASP.NET with some default text or watermark text. This text will be displayed only when the TextBox is empty and out of focus. A typical example can be a Search Box or User Name TextBox. Create a new web form example1.aspx in your asp.net web application project. Add a ASP.NET TextBox control in web form. See below .aspx code for reference:
<asp:TextBox ID="txtName" runat="server" ToolTip="Enter Your Name"></asp:TextBox>
  • In the document.ready() event, retrieve the TextBox control using its client id and save in a local variable for further operations.
  • On the focus event, check if TextBox contains the default text value. If TextBox contains default text value then clear the TextBox . See  below code:
    var txtNameBox = $("#<%=txtName.ClientID%>");
                txtNameBox.focus(function () {
                    if (txtNameBox.val() == this.title)
                        txtNameBox.val("");
               });
    
  • You will notice that I have set ToolTip property of the TextBox. Text (“Enter Your Name”) of the ToolTip property will be displayed as the Watermark text in TextBox. The ToolTip property of the ASP.NET TextBox control is rendered as title at runtime. Therefore, the ToolTip text “Enter Your Name” is retrieved using this.title in above code.
  • On the blur event check whether TextBox control is empty or not. If it is empty then add Watermark text to TextBox control. See below code:
    txtNameBox.blur(function () {
                    if (txtNameBox.val() == "")
                        txtNameBox.val(this.title);
                });
    
  • Call the blur event on page load so that the TextBox control will be out of focus initially.
    txtNameBox.blur();
    

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>This is method 2</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            var txtNameBox = $("#<%=txtName.ClientID%>");
            txtNameBox.focus(function () {
                if (txtNameBox.val() == this.title)
                    txtNameBox.val("");
            });
            txtNameBox.blur(function () {
                if (txtNameBox.val() == "")
                    txtNameBox.val(this.title);
            });
            txtNameBox.blur();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1>This is method 2</h1>
            <asp:TextBox ID="txtName" runat="server" ToolTip="Enter Your Name"></asp:TextBox>
        </div>
    </form>
</body>
</html>
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding!
Read More...

Sunday, 6 October 2013

Beginner’s introduction on how to use jQuery with ASP.NET applications

2 comments
jQuery is a client side open source javascript library which is best to do DOM manipulation, performing AJAX requests, creating various effects or animation and so forth. In this article, I am going to explain how to integrate jQuery with ASP.NET application. I’ll explain how to use jQuery with ASP.NET applications and common tasks which can be accomplished using jQuery library in my upcoming articles. You can also see list of ASP.NET+jQuery tutorials.

Create a new website in visual studio and add a new web form Example1.aspx. Include jQuery source file in web form. You can download latest jQuery from jQuery official website.
<script src="js/jquery-1.8.js"></script>

Executing jQuery code when the DOM is ready

The web form is now ready to use jQuery. We will now embed jQuery code or markup in the following script block:
<script type="text/javascript">
$(document).ready(function () {
            alert(' Alert 2 : DOM is ready to manipulate!');
        });    
</script>
jQuery executes an event named ready() when the DOM is loaded and accessible for manipulation. All the jQuery code which manipulates DOM should be included in the $(document).ready() function. This function gets fired before the page contents and elements are rendered.

Different ways of attaching ready() event :
  1. $(document).ready(function () {
                alert(' Alert 2 : DOM is ready to manipulate!');
            });
    
  2. $(function () {
                alert(' Alert 3 : DOM is ready to manipulate!');
            });
    
  3. $(function ($) {
                alert(' Alert 4 : DOM is ready to manipulate!');
            });
    
Please note that we can attach more than one ready() events to the document. These events are executed in the order they were added into code.

Executing jQuery code when the browser window is completely loaded

As stated earlier, ready() event  will execute code before the browser window loads, but after the DOM is loaded and accessible for manipulation. But, sometimes we can use jQuery to execute code once the entire web page document (including all assets like CSS) is completely loaded.
This functionality can be achieved by attaching a load() event handler to the window object. jQuery provides load() event which invokes a function once the browser window is completely loaded.
$(window).load(function () {
            alert(' Alert 1 : Browser Window and all assets are loaded!');
        });

Executing jQuery code when DOM is parsed without using ready()

  • The ready()  event is not always needed. If jQuery code is not manipulating DOM then you can include it anywhere in the document. This means we can avoid usage of ready() event.
  • We can avoid usage of ready() event even if jQuery code is manipulating DOM.  Simply write your jQuery code in HTML document before the closing </body> element. Since the browser will parse the document from top to bottom, your jQuery code will execute successfully if you have included jQuery code before the closing </body> element. Thus there is no need to use the ready() event.
<script type="text/javascript">
        alert(' Alert 5 : ' + $('p').text());
</script>
Example 1:  Copy and paste below cone in Example1.aspx file.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">

        $(window).load(function () {
            alert(' Alert 1 : Browser Window and all assets are loaded!');
        });

        $(document).ready(function () {
            alert(' Alert 2 : DOM is ready to manipulate!');
        });

        $(function () {
            alert(' Alert 3 : DOM is ready to manipulate!');
        });
        $(function ($) {
            alert(' Alert 4 : DOM is ready to manipulate!');
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>This is sample paragraph text. </p>
        </div>
    </form>
    <script type="text/javascript">
        alert(' Alert 5 : ' + $('p').text());
    </script>
</body>
</html>
Please notice the order in which alert() function is getting executed in above code. Source code can be downloaded from GitHub.


It is recommended to include all CSS files before including jQuery in web page.
Comments and suggestions are most welcome. Happy coding!
Read More...

Saturday, 5 October 2013

Create Dynamic Image Gallery Slideshow using ASP.NET and jQuery Lightbox

11 comments
In my previous post, I've explained how to upload multiple files using ASP.NET 4.5 . In this post, I am going to explain how to create dynamic image gallery using ASP.NET 4.5 and jQuery. The user uploads multiple images at once and those images will be added to a photo gallery or album. As part of uploading image process, we need to store original images on website’s uploads folder. At the same time, we also need to create thumbnail of images. We can divide complete functionality in below three processes:
  1. User uploads multiples images to create a new photo gallery. Store gallery details into database.
  2. Create thumbnail for uploaded images.
  3. Display gallery using jQuery colorbox plugin to get lightbox effect.

Upload multiple images and create gallery

First of all create table tblGallery into database to implement slideshow functionality. SQL Scripts can be downloaded from GitHub.

Column NameData Type
GalleryIdint (set identity property=true)
GalleryNamevarchar(50)
GalleryDescriptionvarchar(500)
GalleryCreatedDatedatetime
Create a new webform CreateAlbum.aspx and write following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateAlbum.aspx.cs" Inherits="CreateAlbum" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create Album</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Gallery Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtGalleryName" runat="server" Width="90%" MaxLength="100">
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvtxtGalleryName" runat="server" ErrorMessage="Enter Gallery Name"
                            ForeColor="Red" ControlToValidate="txtGalleryName">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>Enter Gallery Description
                    </td>
                    <td>
                        <asp:TextBox ID="txtGalleryDescrption" runat="server" TextMode="MultiLine" Width="90%"
                            Height="50px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvtxtGalleryDescrption" runat="server" ErrorMessage="Enter Gallery Description"
                            ForeColor="Red" ControlToValidate="txtGalleryDescrption">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>Upload Photos to Album</td>
                    <td>
                        <asp:FileUpload AllowMultiple="true" ID="MultipleFileUpload" runat="server"></asp:FileUpload></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvFileUploadGallery" runat="server" ErrorMessage="Upload Gallery Photos"
                            ForeColor="Red" ControlToValidate="MultipleFileUpload">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
This webform has two textbox to enter Gallery Name and Gallery description respectively, one file upload control to upload multiple files and one button to submit the data. After completion on .aspx page, write below code on button click event handler in code behind page CreateAlbum.aspx.cs:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            if (MultipleFileUpload.HasFiles)
            {
                int MaxGalleryId, ReturnValue;
                ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
                if (ReturnValue != 0)
                {
                    string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
                    Directory.CreateDirectory(Server.MapPath(GalleryPath));

                    string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
                    Directory.CreateDirectory(Server.MapPath(ThumbnailPath));

                    StringBuilder UploadedFileNames = new StringBuilder();

                    foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
                    {
                        //Upload file
                        string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                        string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
                        uploadedFile.SaveAs(SaveAsImage);

                        //Create thumbnail for uploaded file and save thumbnail on disk
                        Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
                        string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
                        Thumbnail.Save(SaveAsThumbnail);
                    }
                    HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
                }
            }
        }

        catch
        {
            HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
        }
    }
On button click, I am saving gallery details into database table tblGallery and saving images into website’s uploads folder. In the mean time I am also creating thumbnail for image. Refer next section for thumbnail creation.

Creating thumbnail

I've created a function CreateThumbnail which converts given image into thumbnail form. This function accepts below three parameters and returns a bitmap image of the changed thumbnail image which we can save on the disk.
  1. ImagePath : Path of original image
  2. ThumbnailWidth : Required width for thumbnail
  3. ThumbnailHeight : Required height for thumbnail
/// <summary>
    /// CreateThumbnail function returns a Bitmap image of the changed thumbnail image which we can save on the disk.
    /// </summary>
    public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
    {
        System.Drawing.Bitmap Thumbnail = null;
        try
        {
            Bitmap ImageBMP = new Bitmap(ImagePath);
            ImageFormat loFormat = ImageBMP.RawFormat;

            decimal lengthRatio;
            int ThumbnailNewWidth = 0;
            int ThumbnailNewHeight = 0;
            decimal ThumbnailRatioWidth;
            decimal ThumbnailRatioHeight;

            // If the uploaded image is smaller than a thumbnail size the just return it
            if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
                return ImageBMP;

            // Compute best ratio to scale entire image based on larger dimension.
            if (ImageBMP.Width > ImageBMP.Height)
            {
                ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
                ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
                lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
                ThumbnailNewWidth = ThumbnailWidth;
                decimal lengthTemp = ImageBMP.Height * lengthRatio;
                ThumbnailNewHeight = (int)lengthTemp;
            }
            else
            {
                ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
                ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
                lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
                ThumbnailNewHeight = ThumbnailHeight;
                decimal lengthTemp = ImageBMP.Width * lengthRatio;
                ThumbnailNewWidth = (int)lengthTemp;
            }
            Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
            Graphics g = Graphics.FromImage(Thumbnail);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
            g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);

            ImageBMP.Dispose();
        }
        catch
        {
            return null;
        }

        return Thumbnail;
    }

Display gallery using jQuery colorbox plugin

Create new webform Album.aspx to display gallery slideshow using jQuery colorbox plugin. Write following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Album.aspx.cs" Inherits="Album" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>View Gallery</title>
    <script src="js/jquery-1.8.js" type="text/javascript"> </script>
    <script src="js/jquery.colorbox.js" type="text/javascript"></script>
    <script>
        $(document).ready(function () {
            //Examples of how to assign the ColorBox event to elements
            $(".group1").colorbox({ rel: 'group1', transition: "fade", slideshow: "true" });
        });
    </script>
    <link rel="stylesheet" href="css/colorbox.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1><%= GalleryName %></h1>
            <h2><%= GalleryDescription %></h2>
            <asp:DataList ID="dlGallery" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
                Width="100%">
                <ItemTemplate>
                    <table border="1">
                        <tr>
                            <td>
                                <a href='<%#Eval("GalleryImagePath") %>' class='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
                                    <img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
                                </a>
                            </td>
                        </tr>
                        <br />
                    </table>
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>
In above code, I am binding gallery data into datalist and display it using jQuery colorbox plugin.  I’ve added few scripts and css file references in header section of above code. Using these files we can get lightbox slideshow effect.  These files are included in sample code. You can download sample code from GitHub. Another important thing to be noticed is href link tag.
<a href='<%#Eval("GalleryImagePath") %>' class='group1' rel='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
<img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
</a>
  • href='<%#Eval("GalleryImagePath") %>' : This will have image path.  
  • rel='group1' : This allows to group any combination of elements together for a gallery.
  • title='<%= GalleryName %> : <%= GalleryDescription %>' : This attribute is used to display image caption.
On page load following jQuery script is getting executed to assign Colorbox events to elements. For detail documentation about Colorbox plugin check their official page.
<script>
        $(document).ready(function () {
            //Examples of how to assign the ColorBox event to elements
            $(".group1").colorbox({ rel: 'group1', transition: "fade", slideshow: "true" });
        });
</script>
Complete source code and SQL scripts of this tutorial can be downloaded from GitHub. Source code mainly contains three webforms:
  1. CreateAlbum.aspx : To upload images and create gallery.
  2. AlbumList.aspx : To view complete list of created galleries.
  3. Album.aspx : To display images of a specific gallery using lightbox effect.
Please note that this is basic tutorial to create dynamic image gallery slideshow using ASP.NET and jQuery Lightbox. New functionalities like Cover Image for every gallery or different title for every image can be added.
Comments and suggestions are most welcome. Happy coding!
Read More...