Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
I have site account creation with captcha image. When a user clicks the ImageButton (button is used to refresh captcha image: imbReLoad),it will create new a captcha image and my page is not loaded from scratch. it run same javascript.

I used Ajax: script Manager and Update panel with code behind, but when I clicked on the ImageButton imbReLoad to refresh my captcha image, my page did not work.

can you help me, please?
thanks
:confused:
my code behind:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;

public partial class _Default : System.Web.UI.Page
{

    // code create image capchar
    public void TaoAnhCapcha()
    {
        string[] Fonts = { "Arial Black", "Arial" };
        byte bLenght = 6;
        string chars = "12345678ABCDEFGHIJKLMNOPQRSTUVWXYZabdeqptmnghr"; ;
        Bitmap bmp = new Bitmap(125, 30);
        Graphics gr = Graphics.FromImage(bmp);
        // chọn kiểu hiển thị của bipmap kiểu gợn sóng
        // choose type of bipmap
        HatchBrush brush = new HatchBrush(HatchStyle.Wave, Color.White, Color.Wheat);
        gr.FillRegion(brush, gr.Clip);
        //Lưu chuỗi capcha trong quá trình tạo
        StringBuilder strCapCha = new StringBuilder();
        Random Rand = new Random();
        int x = 1;
        for (int i = 0; i < bLenght; i++)
        {
            // Lấy ký tự ngẫu nhiên từ mảng chars
            // get ramdom char
            string schar = chars[Rand.Next(chars.Length)].ToString();
            strCapCha.Append(schar);
            // Tạo font với font ngẫu nhiên chọn từ Fonts
            //create font with ramdom font
            Font font = new Font(Fonts[Rand.Next(Fonts.Length)], 12, FontStyle.Bold | FontStyle.Italic);
            //Lầy kích thước của ký tự
            //get the size of char
            SizeF size = gr.MeasureString(schar, font);
            // Vẽ Ký tự ra ảnh theo thứ tự tăng dần với tọa độ X tăng dần theo i và Y ngẫu nhiên
            //draw char to image
            gr.DrawString(schar, font, Brushes.Blue, x * 2, Rand.Next(2, 10));
            font.Dispose();
            x += 10;
        }
        // Lưu captcha vào session 
        //save capchar to session
        Session["captcha"] = strCapCha.ToString();
        //// Lưu ảnh vào thư mục Capcha với tên ảnh dựa theo IP 
        //save image into folder "hinhtrangtri"
        string path = "hinhtrangtri/" + Request.UserHostAddress + ".gif";
        bmp.Save(Server.MapPath("") + "/" + path, System.Drawing.Imaging.ImageFormat.Gif);
        imgCapcha.ImageUrl = path;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            //call function create image capchar
            TaoAnhCapcha();

        }

    }
    // when user click on this image button, it create new a capchar (the same refresh this image capchar)
    protected void imbReLoad_Click(object sender, ImageClickEventArgs e)
    {
        //CreateCaptcha();
        //call function create image capchar
        TaoAnhCapcha();
    }
    protected void btnRegistry_Click(object sender, EventArgs e)
    {

    }
    protected void DropEmp_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {

    }   
}


code Source of page:
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
    <style type="text/css">
        .style3
        {
            text-align: center;
        }
        .style6
        {
            height: 26px;
        }
        .sitemap
        {
            padding: 10px 10px 15px 5px; text-align: center;overflow: auto;
        }
        </style>

    <p class="style3">
        &nbsp;</p>
    <p class="style3">
        <asp:Label ID="lbtb" runat="server" ForeColor="Red" Text="Label"
            Visible="False"></asp:Label>
    </p>
    <table class="style3" style="margin: 10px">
        <tr>
            <td style="padding-left: 15px" >
                <asp:Label ID="Label2" runat="server" Font-Bold="True" ForeColor="#0000CC"
                    Text="Employee :"></asp:Label></td>
            <td>
                <asp:DropDownList ID="DropEmp" runat="server" Height="23px" Width="200px"
                    AutoPostBack="True"
                    TabIndex="1" onselectedindexchanged="DropEmp_SelectedIndexChanged">
                </asp:DropDownList>
                <asp:Label ID="lbEmpID" runat="server" Enabled="False" ForeColor="#666699"
                    Text="Label" Visible="False"></asp:Label>
            </td>
        </tr>
        <tr>
            <td style="padding-left: 15px">
                <asp:Label ID="Label3" runat="server" Font-Bold="True" ForeColor="#0000CC"
                    Text="UserName :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server" TabIndex="2" Width="250px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td style="padding-left: 15px">
                <asp:Label ID="Label4" runat="server" Font-Bold="True" ForeColor="#0000CC"
                    Text="PassWord :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtPass" runat="server" Width="250px" TabIndex="3"
                    TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style6" style="padding-left: 15px">
                <asp:Label ID="Label6" runat="server" Font-Bold="True" ForeColor="#0000CC"
                    Text="RePassWord :"></asp:Label>
            </td>
            <td class="style6">
                <asp:TextBox ID="txtRepassl" runat="server" Width="250px" TabIndex="4"
                    TextMode="Password"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style6" style="padding-left: 15px">
                <asp:Label ID="Label17" runat="server" Font-Bold="True" ForeColor="#0000CC"
                    Text="Role :"></asp:Label>
            </td>
            <td class="style6">
                <asp:DropDownList ID="DropRole" runat="server" AutoPostBack="True"
                    Height="23px" Width="150px">
                    <asp:ListItem Value="E">Employee</asp:ListItem>
                    <asp:ListItem Value="A">Admin</asp:ListItem>
                    <asp:ListItem></asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td style="padding-left: 15px">
                &nbsp;</td>
            <td  >
                <asp:Image ID="imgCapcha" runat="server" Height="51px" Width="212px" />
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate >
                 &nbsp;&nbsp;&nbsp;
                <asp:ImageButton ID="imbReLoad" runat="server" Height="31px"
                    ImageUrl="~/hinhtrangtri/refresh.png" OnClick="imbReLoad_Click"
                    Width="33px" />
                </ContentTemplate>
              </asp:UpdatePanel>
            </td>
        </tr>
        <tr>
            <td style="padding-left: 15px">
                <asp:Label ID="Label16" runat="server" Font-Bold="True" ForeColor="#0000CC"
                    Text="Input Confirm Chars :"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtmap" runat="server" TabIndex="5"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: center">
                <asp:Button ID="btnRegistry" runat="server" Font-Bold="True" ForeColor="Blue"
                    Height="30px"  Text="Registry"  Width="75px" onclick="btnRegistry_Click"
                    TabIndex="6" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Button ID="btnCancel" runat="server" Font-Bold="True" ForeColor="Blue"
                    Height="29px" Text="Cancel" onclick="btnCancel_Click" TabIndex="7"  />
            </td>
        </tr>
    </table>
    <p>
    </p>

    </div>
    </form>
</body>
</html
Posted
Updated 9-Feb-11 1:35am
v4
Comments
Prerak Patel 9-Feb-11 4:49am    
What do you mean by "my page is not worked"?
Sunasara Imdadhusen 9-Feb-11 7:35am    
Added code formatting!
Sunasara Imdadhusen 9-Feb-11 7:40am    
Do you have any error or problem?
Shahriar Iqbal Chowdhury/Galib 9-Feb-11 9:47am    
I can see script Manager but no update panel
ngthtra 10-Feb-11 3:15am    
I do not have any error and i used Ajaxed Extensions available in VS 2008.

Rearrange your UpdatePanel like following:

XML
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                       <ContentTemplate>
                           <asp:Image ID="imgCapcha" runat="server" Height="51px" Width="212px" />
                       </ContentTemplate>
                       <Triggers>
                           <asp:AsyncPostBackTrigger ControlID="imbReLoad" />
                       </Triggers>
                   </asp:UpdatePanel>
                   <asp:ImageButton ID="imbReLoad" runat="server" Height="31px" ImageUrl="~/hinhtrangtri/refresh.png"
                       OnClick="imbReLoad_Click" Width="33px" />


Replace your TaoAnhCapcha():
public void TaoAnhCapcha()
   {
       string[] Fonts = { "Arial Black", "Arial" };
       byte bLenght = 6;
       string chars = "12345678ABCDEFGHIJKLMNOPQRSTUVWXYZabdeqptmnghr"; ;
       Bitmap bmp = new Bitmap(125, 30);
       Graphics gr = Graphics.FromImage(bmp);
       HatchBrush brush = new HatchBrush(HatchStyle.Wave, Color.White, Color.Wheat);
       gr.FillRegion(brush, gr.Clip);
       StringBuilder strCapCha = new StringBuilder();
       Random Rand = new Random();
       int x = 1;
       for (int i = 0; i < bLenght; i++)
       {
           string schar = chars[Rand.Next(chars.Length)].ToString();
           strCapCha.Append(schar);
           Font font = new Font(Fonts[Rand.Next(Fonts.Length)], 12, FontStyle.Bold | FontStyle.Italic);
           SizeF size = gr.MeasureString(schar, font);
           gr.DrawString(schar, font, Brushes.Blue, x * 2, Rand.Next(2, 10));
           font.Dispose();
           x += 10;
       }
       //save capchar to session
       Session["captcha"] = strCapCha.ToString();
       //save image into folder "hinhtrangtri"
       if (Session["path"] != null)
       {
           System.IO.File.Delete(Server.MapPath("") + "/" + Session["path"].ToString());
       }
       string path = "hinhtrangtri/" + Request.UserHostAddress + Rand.Next(100) + ".gif";
       bmp.Save(Server.MapPath("") + "/" + path, System.Drawing.Imaging.ImageFormat.Gif);
       imgCapcha.ImageUrl = path;
       Session["path"] = path;
   }


======================
Working?
 
Share this answer
 
v3
Comments
ngthtra 10-Feb-11 5:41am    
your way is not resolved my problem, imgCapcha is not reload content of new capchar.
Monjurul Habib 10-Feb-11 7:33am    
i ran the code on my local pc and it was fine.
can you please comment the last line, run the solution and go the directory where the image supposed to create and check any image is created or not?
ngthtra 11-Feb-11 6:35am    
when ran,image is created and the content of image capchar is changed when clicked on button imbReLoad but it is not loaded on my page. what is the problem in here?
Monjurul Habib 11-Feb-11 7:23am    
did you arrange your UpdatePanel according to the code above(.aspx page) ?
karthick meiyappan 6-Feb-13 5:07am    
i used the lastly given .aspx steps.but its not working fine
Hi

Move this....

<asp:Image ID="imgCapcha" runat="server" Height="51px" Width="212px" />

inside the content template in the update panel.

The image is not refreshing because of the client side caching.
If you try

string path = "hinhtrangtri/" + Request.UserHostAddress +Rand.Next(100).ToString()+ ".gif";
it will work. But it generate lot of images.

Try clear the cache before update the image.
 
Share this answer
 
Hello,

There is a famous browser "trick" for image refresh w/o page postback.
I guess it's pretty common now because I see lots of posts on this method.

This way you can avoid generating lot of images.

Replace
imgCapcha.ImageUrl = path;

with

imgCapcha.ImageUrl = path + "?t="+DateTime.Now.Ticks.ToString();


It should do.


you still have to move this
XML
<asp:Image ID="imgCapcha" runat="server" Height="51px" Width="212px" />

to inside the content template in the update panel.



Happy coding~ :laugh:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900