articles

Home / DeveloperSection / Articles / Lightbox with reCaptcha in ASP.NET

Lightbox with reCaptcha in ASP.NET

AVADHESH PATEL7941 07-Aug-2012

This article describes Lightbox as a simple, unobtrusive script used to overlay images on the current page. It delivers a nice, professional looking method for displaying images as overlays through the use of hyperlinks. Lightbox allows the developer the option of displaying images singly or in sequence. Images grouped into sequences may be viewed by the user in a slideshow like presentation that the user can control with either the mouse or the left and right arrow keys.

But here I’m going to describe how to use Lightbox as for taking input and populate to GridView Control and database. Here I used validation and captcha in Lightbox. Steps are given below:

Step 1:- Create a table in SqlServer and ‘id’ column make automatic generated.

Lightbox with reCaptcha in ASP.NET

Step 2:- Create a web page and take one GridView (for display populated records) and one HyperLink (for opening Lightbox).

Step 3:- Download reCaptcha from given link and save it on your local system.

http://www.google.com/recaptcha/whyrecaptcha

Step 4:- Now click on Add Reference… and select recently downloaded reCaptcha.dll file.

Step 5:- Now write down the following code on .aspx page where you want to bind GridView, design Lightbox and adds Google reCaptcha with proper validation.

 <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs" Inherits="_Default"%>

<%@RegisterTagPrefix="recaptcha"Namespace="Recaptcha"Assembly="Recaptcha"%>

 

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

    <title>LIGHTBOX EXAMPLE</title>

  <%--  class for LightBox--%>

    <styletype="text/css">

        .black_overlay

        {

            display: none;

            position: absolute;

            top: 0%;

            left: 0%;

            width: 100%;

            height: 100%;

            background-color: black;

            z-index: 1001;

            -moz-opacity: 0.8;

            opacity: .60;

            filter: alpha(opacity=80);

        }

       

        .white_content

        {

            display: none;

            position: absolute;

            top: 15%;

            left: 35%;

            width: 30%;

            padding: 0px;

            border: 0pxsolid#a6c25c;

            background-color: white;

            z-index: 1002;

            overflow: auto;

        }

       

        .headertext

        {           

            font-family: TimesNewRoman,Helvetica,sans-serif;

            font-size: 14px;

            color: teal;

            font-weight: bold;

        }

       

        .textfield

        {

            border: 1pxsolid#a6c25c;

            width: 135px;

        }

       

        .button2

        {

            background-color: Teal;

            color: White;

            font-size: 11px;

            font-weight: bold;

            border: 1pxsolid#7f9db9;

            width: 68px;

        }

    </style>

</head>

<body>

 

    <formid="form1"runat="server">

   <%-- function for clear lightbox textbox values and call lightbox--%>

    <scripttype="text/javascript"language="javascript">

        function ClearTextboxes()

        {

            document.getElementById('txtlbName').value = '';

            document.getElementById('txtlbAge').value = '';

            document.getElementById('txtlbSalary').value = '';

            document.getElementById('txtlbCountry').value = '';

            document.getElementById('txtlbCity').value = '';

            document.getElementById('light').style.display = 'none';

            document.getElementById('fade').style.display = 'none';                           

        }

    </script>

 

    <divid="light"class="white_content">

        <divalign="center"class=" headertext">

        </div>

        <div>

            <tablewidth="100%"  style=" background-color: Black; z-index: 1001;  -moz-opacity: 0.8; opacity: .60; filter: alpha(opacity=80); "height="27">

                <tr>

                    <tdstyle="width: 50%"></td>

                    <tdstyle="float: right; width:50%; margin-right:-2px"height="6px">

                        <ahref="javascript:void(0)"onclick="ClearTextboxes()">

                            <imgsrc="images/close.png"style="border: 0px"width="32px"align="right"height="32px"/></a>

                    </td>

                </tr>

            </table>

        </div>

<%--        table with asp.net controls in lightbox--%>

        <tablecellpadding="0"cellspacing="0"border="0"style="background-color: teal"

            width="100%">

            <tr>

                <tdstyle="padding: 4px;">

                    <tablealign="center"border="0"cellpadding="0"cellspacing="0"style="background-color: #fff"

                        width="100%">

                        <tr>

                            <tdalign="center"colspan="0"class="headertext"style="border-bottom: 1px solid teal;">

                            <br/>

                                User Information

                            </td>

                        </tr>

                        <tr>

                            <td>

                                &nbsp;

                            </td>

                        </tr>

                        <tr>

                            <tdalign="center">

                                <table>

                                    <tr>

                                        <tdalign="right">

                                            Name:

                                        </td>

                                        <td>

                                    <%--   script for Name validation--%>

                                        <scriptlanguage="javascript"type="text/javascript">

                                            function Name_Validation(e) {

                                                if ((event.keyCode > 97) && (event.keyCode <= 123)) {

                                                    returntrue;

                                                }

                                                elseif ((event.keyCode >= 65) && (event.keyCode <= 97)) {

                                                    returntrue;

                                                }

                                                elseif (event.keyCode == 32) {

                                                    returntrue;

                                                }

                                                else {

                                                    alert('Please enter alphabate only');

                                                    returnfalse;

                                                }

                                            }

                                          </script>

                                          <%--script for trim space--%>

                                          <scripttype="text/javascript">

                                              function trim(stringToTrim) {

                                                  return stringToTrim.replace(/^\s+|\s+$/g, "");

                                              }

 

                                              function RemoveSpace(id) {

                                                  if (id != null)

                                                      id.value = trim(id.value);

                                              }

  

                                          </script>

                                            <asp:TextBoxID="txtlbName"runat="server"MaxLength="50"OnKeyPress="return Name_Validation(this);"onblur="RemoveSpace(this)" CssClass="textfield"></asp:TextBox>

                                        </td>

                                        <td>

                                            <asp:RequiredFieldValidatorID="rfvtxtlbName"runat="server"Text="*"ToolTip="Enter name"

                                                ControlToValidate="txtlbName"></asp:RequiredFieldValidator>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdheight="10px">

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdalign="right">

                                            Age:

                                        </td>

                                        <td>

                                        <%--script for age validation--%>

                                        <scriptlanguage="javascript"type="text/javascript">

                                            function Age_Validation(e) {

                                                if ((event.keyCode >= 48) && (event.keyCode <= 57)) {

                                                    returntrue;

                                                }

                                                else {

                                                    alert('Please enter numeric value');

                                                    returnfalse;

                                                }

                                            }

                                        </script>

                                                                      

                                            <asp:TextBoxID="txtlbAge"runat="server"MaxLength="2"CssClass="textfield"OnKeyPress="return Age_Validation(this);"></asp:TextBox>

                                        </td>

                                        <td>

                                            <asp:RequiredFieldValidatorID="rfvtxtlbAge"runat="server"Text="*"ToolTip="Enter age"

                                                ControlToValidate="txtlbAge"></asp:RequiredFieldValidator>

                                            <asp:RangeValidatorID="rrvtxtlbAge"runat="server"Text="*"MaximumValue="99"MinimumValue="15"Display="Dynamic"ControlToValidate="txtlbAge"Type="Integer"ToolTip="Min age 15 & Max age 99"></asp:RangeValidator>

                                            <asp:LabelID="lblErrorMsg"runat="server"Text="Min age 15 & Max age 99"Visible="false"></asp:Label>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdheight="10px">

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdalign="right">

                                            Salary:

                                        </td>

                                        <td>

                                        <%--script for salary validator or numeric values validator--%>

                                         <scriptlanguage="javascript"type="text/javascript">

                                             function Salary_Validation(e) {

                                                 if ((event.keyCode >= 48) && (event.keyCode <= 57)) {

                                                     returntrue;

                                                 }

                                                 else {

                                                     alert('Please enter numeric value');

                                                     returnfalse;

                                                 }

                                             }

                                         </script>

 

                                        <%-- Convert into Money Formate--%>

                                        <scripttype="text/javascript">

 

                                            function formatCurrency(usFormat) {

 

                                                usFormat = usFormat.toString().replace(/\$|\,/g, '');

 

                                                if (isNaN(usFormat)) {

                                                    usFormat = "0";

                                                }

                                                sign = (usFormat == (usFormat = Math.abs(usFormat)));

 

                                                usFormat = Math.floor(usFormat * 100 + 0.50000000001);

 

                                                cents = usFormat % 100;

 

                                                usFormat = Math.floor(usFormat / 100).toString();

 

                                                if (cents < 10) {

                                                    cents = "0" + cents;

                                                }

                                                for (var i = 0; i < Math.floor((usFormat.length - (1 + i)) / 3); i++) {

                                                    usFormat = usFormat.substring(0, usFormat.length - (4 * i + 3)) + ',' + usFormat.substring(usFormat.length - (4 * i + 3));

                                                }

                                                return (((sign) ? '' : '-') + usFormat + '.' + cents);

                                            }

                                        </script>

                                            <asp:TextBoxID="txtlbSalary"runat="server"MaxLength="10"CssClass="textfield"OnKeyPress="return Salary_Validation(this);"onblur="this.value=formatCurrency(this.value);"></asp:TextBox>

                                        </td>

                                        <td>

                                            <asp:RequiredFieldValidator ID="rfvtxtlbSalary"runat="server"Text="*"ToolTip="Enter salary"

                                                ControlToValidate="txtlbSalary"></asp:RequiredFieldValidator>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdheight="10px">

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdalign="right">

                                            Country:

                                        </td>

                                        <td>

                                        <%--script for alphabate enter in textbox--%>

                                        <scriptlanguage="javascript"type="text/javascript">

                                            function Country_Validation(e) {

                                                if ((event.keyCode > 97) && (event.keyCode <= 123)) {

                                                    returntrue;

                                                }

                                                elseif ((event.keyCode >= 65) && (event.keyCode <= 97)) {

                                                    returntrue;

                                                }

                                                else {

                                                    alert('Please enter Alphabate only');

                                                    returnfalse;

                                                }

                                            }

                                        </script>

                                            <asp:TextBoxID="txtlbCountry"runat="server"MaxLength="20"CssClass="textfield"OnKeyPress="return Country_Validation(this);"></asp:TextBox>

                                        </td>

                                        <td>

                                            <asp:RequiredFieldValidatorID="rfvtxtlbCountry"runat="server"Text="*"ToolTip="Enter country"

                                                ControlToValidate="txtlbCountry"></asp:RequiredFieldValidator>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdheight="10px">

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdalign="right">

                                            City:

                                        </td>

                                        <td>

                                         <%--script for alphabate enter in textbox--%>

                                         <scriptlanguage="javascript"type="text/javascript">

                                             function City_Validation(e) {

                                                 if ((event.keyCode > 97) && (event.keyCode <= 123)) {

                                                     returntrue;

                                                 }

                                                 elseif ((event.keyCode >= 65) && (event.keyCode <= 97)) {

                                                     returntrue;

                                                 }

                                                 else {

                                                     alert('Please enter Alphabate only');

                                                     returnfalse;

                                                 }

                                             }

                                        </script>

                                            <asp:TextBoxID="txtlbCity"runat="server"MaxLength="20"CssClass="textfield"OnKeyPress="return City_Validation(this);"></asp:TextBox>

                                        </td>

                                        <td>

                                            <asp:RequiredFieldValidatorID="rfvtxtlbCity"runat="server"Text="*"ToolTip="Enter city"

                                                ControlToValidate="txtlbCity"></asp:RequiredFieldValidator>

                                        </td>

                                    </tr>

                                    <tr>

                                        <tdheight="10px"></td>

                                    </tr>

                                    <tr>

                                    <%--reCaptcha control--%>

                                        <table>

                                        <tr>

                                            <tdalign="center">

                                               <recaptcha:RecaptchaControl

                                                  ID="recaptcha"

                                                  runat="server"

                                                  PublicKey="6LfqmdQSAAAAAHcyeGDCoLodLISt4d3LyC5ghIOS"

                                                  PrivateKey="6LfqmdQSAAAAAFkZJAH9zivztO5VSwwJp_9XxcAt"/>

                                               <asp:LabelID="lblResult"runat="server"Text="Label"Visible="false"></asp:Label>

                                                 

                                            </td>

                                        </tr>

                                        </table>

                                    </tr>

                                    <tr>

                                        <tdheight="10px"align="center"><asp:ButtonID="btnlbAdd"runat="server"Text="Add"OnClick="AddNewRecord"class="button2"/></td>

                                    </tr>

                                    <tr>

                                    <tdalign="center">

                                                                        

                                    </td>

                                    </tr>

                                    <tr>

                                        <tdheight="10px"></td>

                                    </tr>

                                    <tr>

                                        <tdalign="center"></td>                                        

                                   </tr>

                                  

                                </table>

                            </td>

                        </tr>

                        <tr>

                            <tdheight="10px">

                            </td>

                        </tr>

                    </table>

                </td>

            </tr>

        </table>

        <asp:LabelID="txtlbl"runat="server"></asp:Label></div>

    <divid="fade"class="black_overlay">

    </div>

    <%--GridView with asp.net control for bind record from database--%>

    <div>

        <asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"OnRowDeleting="RowDeleting"

            CellPadding="4"EnableModelValidation="True"GridLines="None"Width="1297px"

            ForeColor="#333333">

            <RowStyleHorizontalAlign="Center"/>

            <AlternatingRowStyleBackColor="White"/>

            <EditRowStyleBackColor="#7C6F57"/>

            <FooterStyleBackColor="#1C5E55"ForeColor="White"Font-Bold="True"/>

            <HeaderStyleBackColor="#1C5E55"Font-Bold="True"ForeColor="White"/>

            <PagerStyleBackColor="#666666"ForeColor="White"HorizontalAlign="Center"/>

            <RowStyleBackColor="#E3EAEB"/>

            <SelectedRowStyleBackColor="#C5BBAF"Font-Bold="True"ForeColor="#333333"/>

            <Columns>

                <asp:TemplateField>

                    <HeaderTemplate>

                        Id</HeaderTemplate>

                    <ItemTemplate>

                        <asp:LabelID="lblId"runat="server"Text='<%#Bind("id")%>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <HeaderTemplate>

                        Name</HeaderTemplate>

                    <ItemTemplate>

                        <asp:LabelID="lblName"runat="server"Text='<%#Bind("name") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <HeaderTemplate>

                        Age</HeaderTemplate>

                    <ItemTemplate>

                        <asp:LabelID="lblAge"runat="server"Text='<%#Bind("age") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <HeaderTemplate>

                        Salary</HeaderTemplate>

                    <ItemTemplate>

                        <asp:LabelID="lblSalary"runat="server"Text='<%#Bind("salary") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <HeaderTemplate>

                        Country</HeaderTemplate>

                    <ItemTemplate>

                        <asp:LabelID="lblCountry"runat="server"Text='<%#Bind("country") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <HeaderTemplate>

                        City</HeaderTemplate>

                    <ItemTemplate>

                        <asp:LabelID="lblCity"runat="server"Text='<%#Bind("city") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <HeaderTemplate>

                        Operation</HeaderTemplate>

                    <ItemTemplate>

                        <asp:ButtonID="btnDelete"runat="server"CommandName="Delete"Text="Delete"CausesValidation="true"

                            OnClientClick="return confirm('Are you sure?')"/>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

            <EmptyDataTemplate>

                No record available

            </EmptyDataTemplate>

        </asp:GridView>

        </br>

    <%--    hyperlink for display lightbox--%>

        <ahref="javascript:void(0)"onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">

            Add New Record</a></div>

    </form>

</body>

</html>

Step 6:- For displaying records in GridView and Opening Lightbox and to validate the reCaptcha, write down the following code in “.cs” file.

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.UI.WebControls;

 

publicpartial class_Default : System.Web.UI.Page

{

    protectedvoid Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            FillGridView();

        }

    }

 

    ///<summary>

    /// function for fill gridview

    ///</summary>

    publicvoid FillGridView()

    {

        try

        {

            string cnString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

            SqlConnection con = newSqlConnection(cnString);

            GlobalClass.adap = newSqlDataAdapter("select * from gridview", con);

            SqlCommandBuilder bui = new SqlCommandBuilder(GlobalClass.adap);

            GlobalClass.dt = newDataTable();

            GlobalClass.adap.Fill(GlobalClass.dt);

            GridView1.DataSource = GlobalClass.dt;

            GridView1.DataBind();

        }

        catch

        {

 

        }

    }

 

    ///<summary>

    /// adding new record from lightbox page

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protectedvoid AddNewRecord(object sender, EventArgs e)

    {

        recaptcha.Validate();

        if (Page.IsValid)

        {

            DataRow dr = GlobalClass.dt.NewRow();

            dr[1] = txtlbName.Text.Trim();

            dr[2] = txtlbAge.Text.Trim();

            dr[3] = txtlbSalary.Text.Trim();

            dr[4] = txtlbCountry.Text.Trim();

            dr[5] = txtlbCity.Text.Trim();

            txtlbName.Text = txtlbAge.Text = txtlbAge.Text = txtlbSalary.Text = txtlbCountry.Text = txtlbCity.Text = "";

            GlobalClass.dt.Rows.Add(dr);

            GridView1.DataSource = GlobalClass.dt;

            GlobalClass.adap.Update(GlobalClass.dt);

            GridView1.DataBind();

            FillGridView();

            lblResult.Visible = false;

        }

 

        else

        {

 

            lblResult.Visible = true;

            lblResult.Text = "Please input correct image value!";

            lblResult.ForeColor = System.Drawing.Color.Red;

            ClientScript.RegisterStartupScript(GetType(), "JavaScript", "javascript: document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'", true);

        }

 

    }

 

 

 

    ///<summary>

    /// Deleting record from gridview

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protectedvoid RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        try

        {

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();

            GlobalClass.adap.Update(GlobalClass.dt);

            FillGridView();

        }

        catch

        {

 

        }

    }

}

Step 7:- Compile and run the webpage and click Hyperlink control “Add New Record”

Lightbox with reCaptcha in ASP.NET

Step 8:- Now a Lightbox popup and require for proper inputs.

Lightbox with reCaptcha in ASP.NET

 Step 9:- For Example I fill record and click button “add”. If all inputs in a proper way then Lightbox will be closed and records are populated in GridView. 

Lightbox with reCaptcha in ASP.NET

Lightbox with reCaptcha in ASP.NET

Note: - Here “Id” automatic generated in database when any new record entered.



Updated 07-Sep-2019
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By