Problem with recaptchacontrol inside updatepanel - c#

I have a recaptchavalidator, which is inside an updatepanel:
<asp:updatepanel runat=server id=updatepanel1>
<cc1:recaptchacontrol runat=server publickey=.. privatekey=.. id=recaptchavalidator1/>
<asp:button runat=server id=button1/>
</updatepanel>
I am sure that some of you can guess what happens. For those of you who haven't experienced this before, the recaptchacontrol disappears! I have tried redirecting to the same page if the recaptchacontrol returns a false validation, but this has resulted in complex codebehind, and loss of veiwstate.
Is there a simple solution to this? I have looked over some articles on the web, but they seem to be complex and not well structured. I need to change the content of the updatepanel, so keep this in mind.
Thank you for your help.

I got this to work nicely with just one updatepanel.
<recaptcha:RecaptchaControl Theme="white" ID="recaptcha" runat="server" PrivateKey="your_pub_key "
PublicKey="your_pub_key" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Visible="false" ID="RecaptchaResult" runat="server" />
<asp:Button ID="RecaptchaButton" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
The key is to have your updatepanel set to conditional around your post button, so that you manually call the update to reload the recaptcha control from the server side.
Then, you call .update() on your panel after you've asked for the reload();
protected void btnSubmit_Click(object sender, EventArgs e)
{
recaptcha.Validate();
if (recaptcha.IsValid)
{
RecaptchaResult.Text = "Success";
RecaptchaResult.Text = "You got it!";
RecaptchaResult.ForeColor = System.Drawing.Color.Green;
RecaptchaResult.Visible = true;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "recaptcha", "recaptcha.reload();", true);
UpdatePanel1.Update();
}
else
{
RecaptchaResult.Text = this.recaptcha.ErrorMessage;
RecaptchaResult.ForeColor = System.Drawing.Color.Red;
RecaptchaResult.Visible = true;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "recaptcha", "recaptcha.reload();", true);
UpdatePanel1.Update();
}
}

Here is the answer that I have tried and is working:
ASP.Net, disappearing Recaptcha, UpdatePanels and Partial PostBacks: Fixed once and for all
Basically it involves creating a hidden div and using jquery to re-render the html. Also the blog post gives a nice little breakdown of the typical solutions (e.g., using RegisterClientScriptBlock with a simple reload) and why they fail.
<div runat="server" id="pbTarget" visible="false"></div>
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" Theme="clean" />
code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
recaptcha.Validate();
if (!Page.IsValid || !recaptcha.IsValid)
{
pbTarget.Visible = true;
ScriptManager.RegisterClientScriptBlock(
recaptcha,
recaptcha.GetType(),
"recaptcha",
"Recaptcha._init_options(RecaptchaOptions);"
+ "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
+ "{"
+ " if ( RecaptchaOptions.custom_theme_widget )"
+ " {"
+ " Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
+ " Recaptcha.challenge_callback();"
+ " }"
+ "} else {"
+ " if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
+ " {"
+ " jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
+ " Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
+ " }"
+ " Recaptcha.reload();"
+ " Recaptcha.challenge_callback();"
+ "}",
true
);
return;
}
else
{
//normal page processing here...

Try this.
<asp:UpdatePanel ID="ContactUpdatePanel" runat="server">
<ContentTemplate>
<p>
<label>Name:</label>
<asp:TextBox ID="txtName" runat="server"
CssClass="textbox">
</asp:TextBox>
</p>
<p>
<label>Address</label>
<asp:TextBox ID="txtAddress" runat="server"
CssClass="textbox"
Height="50px"
TextMode="MultiLine">
</asp:TextBox>
</p>
<p>
<recaptcha:RecaptchaControl ID="recaptcha" runat="server"
PublicKey="public key"
PrivateKey="private key"
Theme="white" />
</p>
<p>
<asp:UpdatePanel ID="UpdatePanel2" runat="server"
ChildrenAsTriggers="false"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="ErrorLabel" runat="server"
EnableViewState="false"
ForeColor="Red" />
</ContentTemplate>
</asp:UpdatePanel>
<p>
</p>
<p>
<asp:Button ID="SubmitButton" runat="server"
onclick="SubmitButton_Click" Text="Submit" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
Code-behind
protected void SubmitButton_Click(object sender, EventArgs e)
{
try
{
this.recaptcha.Validate();
if (recaptcha.IsValid)
{
//valid form. post it
}
else
{
ErrorLabel.Text = "Invalid Captcha. Please re-enter the words.";
ScriptManager.RegisterClientScriptBlock(
this.Page,
this.Page.GetType(),
"mykey",
"Recaptcha.reload();",
true);
UpdatePanel2.Update();
}
}
catch (Exception exception)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
}

Related

C# ASP.NET - Not able to hide image in updateprogress after response redirect

I have one Ajax UpdateProgress for only one UpdatePanels in the page.
The updatepanel has a gridview with a download button.
Once user clicks on the button, the 'wait' Image shows up, but keeps showing even after the download is complete.
How should I hide it, once the download is done.
My code below but not working, because the image is showing even after the download is complete.
.cs
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton ImageButton1 = (ImageButton)sender;
sIDint = ImageButton1.CommandArgument.ToString();
Thread.Sleep(3000);
HttpCookie cookie = new HttpCookie("ExcelDownloadFlag")
{
Value = "Flag",
Expires = DateTime.Now.AddDays(1)
};
Response.AppendCookie(cookie);
Response.Redirect("pdf.aspx?sID=" + sIDint.ToString());
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "HideImage();", true);
ImageButton imgLike = (ImageButton)FindControl("imgLike");
if (imgLike != null)
{
imgLike.Visible = false;
}
}
.aspx
function HideImage() {
$(#imgLike).hide();
}
<asp:TemplateField HeaderText="Dwn">
<ItemTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<div class="modal">
<div class="center">
<img alt="" src="/Img/ajax-loader.gif" id="imgLike" />
</div>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ImageButton1" />
</Triggers>
<ContentTemplate>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="/img/download.gif"
OnClick="ImageButton1_Click"
CommandArgument='<%# Eval("ID") %>' />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
Edit
Solved using
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton ImageButton1 = (ImageButton)sender;
string sIDint = ImageButton1.CommandArgument.ToString();
Thread.Sleep(3000);
HttpCookie cookie = new HttpCookie("ExcelDownloadFlag")
{
Value = "Flag",
Expires = DateTime.Now.AddDays(1)
};
Response.AppendCookie(cookie);
ScriptManager.RegisterStartupScript(this, typeof(string), "OpenWindow", "window.open('pdf.aspx?sID=" + sIDint + "');", true);
}

ASP.NET TextBox won't add text from C#

I am trying to do a multi Client - Server application. After I did some of the basic controls and functions with Windows Forms I thought to add a WebPage to my Client side.
I created a new project and edited it and it works ok, the page is connecting to the server and it receives the messages I send from the web page.
The problem I get when I need to post messages on a textbox on the web page. I searched on some pages here, on the internet and I can't find a good solution for my problem. I alose used the Page.IsPostBack but it didn't work, then I added an UpdatePanel because the page was refreshing when I clicked the buttons but that didn't work either... Now I am out of ideas.
Can anybody suggest how should I do this ? My code behind is C# and I don't know how to parse these details to JavaScript or jQuery, so any of you have some details on how to that it will also be appreciated.
Thanks in advance.
And also I will post anything needed if there is important for this question.
EDIT (Added code):
public void btnSend_Click(object sender, EventArgs e)
{
if (tbSendMessage.Text.Length > 0)
{
string message = tbSendMessage.Text;
byte[] outStream = Encoding.ASCII.GetBytes(message + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbSendMessage.Text = string.Empty;
}
}
private void getMessage()
{
while (true)
{
try
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[70000];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
//tbReceivedMessages.Text += returndata + "\n";
ShowMessage(returndata);
}
catch (Exception ex)
{
ShowAlert("Connection lost.\n" + ex.Message);
//ShowMessage("Conexiunea cu serverul s-a pierdut.\n" );
serverStream.Close();
return;
}
}
}
private void ShowMessage(string message)
{
sb.AppendLine(message);
tbReceivedMessages.Text += sb;
}
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %></h2>
<p>
<asp:UpdatePanel ID="UpdatePanelConnect" runat="server">
<ContentTemplate>
<asp:Label ID="lblUsername" runat="server" Text="Enter username:"></asp:Label>
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
<asp:Button ID="btnConnect" runat="server" OnClick="btnConnect_Click" Text="Connect" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
<p> </p>
<p>
<asp:UpdatePanel ID="UpdatePanelConnected" runat="server">
<ContentTemplate>
<asp:TextBox
ID="tbReceivedMessages"
runat="server"
Height="250px"
TextMode="MultiLine"
Width="250px"
MaxLength="2000000"
ReadOnly="True"></asp:TextBox>
</p>
<p> </p>
<p>
<asp:TextBox ID="tbSendMessage" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
</asp:Content>
If you want two server controls to communicate each other via Ajax, you will need to place them in same UpdatePanel.
FYI: If you are new to ASP.Net Web Form, do not use UpdatePanel yet. Instead, make it work with regular post back.
<asp:UpdatePanel ID="UpdatePanelConnect" runat="server">
<ContentTemplate>
<asp:Label ID="lblUsername" runat="server" Text="Enter username:"></asp:Label>
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
<asp:Button ID="btnConnect" runat="server" OnClick="btnConnect_Click" Text="Connect" />
<asp:TextBox
ID="tbReceivedMessages"
runat="server"
Height="250px"
TextMode="MultiLine"
Width="250px"
MaxLength="2000000"
ReadOnly="True"></asp:TextBox>
</p>
<p> </p>
<p>
<asp:TextBox ID="tbSendMessage" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
public void btnSend_Click(object sender, EventArgs e)
{
if (tbSendMessage.Text.Length > 0)
{
string message = tbSendMessage.Text;
// This code won't work.
/*byte[] outStream = Encoding.ASCII.GetBytes(message + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbSendMessage.Text = string.Empty;*/
}
}

File uploading in update panel still refreshing

I search over internet to use upload file in update panel.
I want to avoid page refreshing when i click on file upload.
So i put my codes in update panel with a trigger
but still refreshing ...
Codes :
<asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:PostBackTrigger ControlID="imageUploadAction" />
</Triggers>
<ContentTemplate>
<div class="fileUpload btn btn-primary btn-block btn-lg">
<span>آپلود</span>
<asp:FileUpload CssClass="inputfile" runat="server" ID="imageUpload" />
</div>
<br />
<div class="alert alert-info" runat="server" id="imageAlert"></div>
<div style="border-bottom: 1px solid #ddd;"></div>
<br />
<asp:Button runat="server" ID="imageUploadAction" CssClass="btn btn-block btn-lg btn-success" Text="ارسال" OnClick="imageUploadAction_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Behind Code :
protected void imageUploadAction_Click(object sender, EventArgs e)
{
Debug.WriteLine("Uploading" + " " + imageUpload.HasFile);
Boolean fileOK = false;
String path = Server.MapPath("~/Assets/image/posts/");
if (imageUpload.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(imageUpload.FileName).ToLower();
String[] allowedExtensions = { ".jpg", ".png" };
for (int i = 0; i < allowedExtensions.Length; i++)
if (fileExtension == allowedExtensions[i])
fileOK = true;
}
if (fileOK)
{
try
{
int last = getLastImage() + 1;
string link = path + last + ".jpg";
imageUpload.PostedFile.SaveAs(link);
db.insertPhoto(link);
imageAlert.InnerText = "فایل آپلود شده است ، کد عکس : " + last;
}
catch (Exception ex)
{
ExceptionUtility.LogExceptionNotFailure(ex);
Debug.WriteLine(ex.ToString());
imageAlert.InnerText = "فایل نمیتواند آپلود شود.";
}
}
else
{
imageAlert.InnerText = "فایل مجاز نیست";
}
}
You're setting up the imageUploadAction button to be a PostBackTrigger (thus not async) which causes a full reload of the page.
Note that there is no way to use a regular uploader using an UpdatePanel. If you really want asynchronous file upload, you'll have to implement quite a bit of code both on the client and the server side.
Take a look at FlowJs here
https://github.com/flowjs/flow.js
with a demo here
http://flowjs.github.io/ng-flow/
Hope that helps

ASP.NET C# Update Panel, File Upload Control and maintaining and saving information on postback

I am designing a web page in asp.net C# named "myprofile". The structure is as follows from top to bottom: file upload control(for logo), drop down (for hotel type), a rich text box (for contact information - extra: bold, italics, hyperlink etc features), drop down (for location).
My problem is maintaining the values of file upload control and rich text box on postback. Also I am unable to insert the values in database as nothing is happening. I tried many things. Finally, I set my design as follows:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-1</legend>
<br />(Type of Hotel)<br /><br />
<asp:DropDownList ID="DropDownTypeOfHotel" runat="server" CssClass="cssdropdown"></asp:DropDownList>
<br />(Contact Information Here)<br /><br />
<asp:TextBox ID="RichTextBoxContactInfo" runat="server"></asp:TextBox>
<br />(Location)<br /><br />
<asp:DropDownList ID="DropDownListLocation" runat="server" CssClass="cssdropdown"></asp:DropDownList>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-2</legend>
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
<br /><br />
<asp:Button ID="btnUpdate2" runat="server" Text="Update Both Panels" OnClick="btnUpdate2_Click" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
My code for the same lies here:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadHotelType();
}
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btnUpdate2_Click(object sender, EventArgs e)
{
if (DropDownTypeOfHotel.SelectedIndex > 0)
{
if (DropDownListLocation.SelectedIndex > 0)
{
if (!string.IsNullOrEmpty(RichTextBoxContactInfo.Text))
{
Label1.Text = "Cool!";
insert();
}
else
{
Label1.Text = "Kindly add contact info!";
}
}
else
{
Label1.Text = "Kindly select location!";
}
}
else
{
Label1.Text = "Kindly select type of hotel!";
}
}
public void loadHotelType()
{
DropDownTypeOfHotel.Items.Insert(0, "--Select Type of Hotel/Supplier--");
DropDownTypeOfHotel.Items.Insert(1, "2 star");
DropDownTypeOfHotel.Items.Insert(2, "3 star");
DropDownTypeOfHotel.Items.Insert(3, "5 star");
DropDownListLocation.Items.Insert(0, "--Select Location of Hotel/Supplier--");
DropDownListLocation.Items.Insert(1, "Canada");
DropDownListLocation.Items.Insert(2, "USA");
DropDownListLocation.Items.Insert(3, "LA");
}
public void insert()
{
int img_logo = 0;
static byte[] btlogo_img;
if (FileUpload1.PostedFile.ContentLength != 0)
{
btlogo_img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile up1 = FileUpload1.PostedFile;
up1.InputStream.Read(btlogo_img, 0, (int)FileUpload1.PostedFile.ContentLength);
img_logo = 1;
}
if (img_logo == 1)
{
con1.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into file values('" + FileUpload1.PostedFile.FileName + "','" + btlogo_img + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
Label1.Text = "Kindly select logo!";
}
}
Kindly suggest me with the same.
The easiest solution I found was to keep the controls, that loses value on postback, outside update panel and keep all other controls inside update panel.
It really worked for me!

two decisons just one button

My problem now is that i need to click 2 time to do the search with right text to search. is there a way to cacth what i'm sending and update it? Is there another solution?
Hello!!
I have 2 radiobuttons that decides what search engine to use (google or mine), and i have 1 button that will submit a text that will be used to be searched in one of the 2 search engines. When i try to do the google search, the first time it just opens the new window when i click the 2nd time, it opens the google window with word that i want to search and if i try to do my search it do the both searchs. What i'm doing wrong ? how i put this working in the right way?
<table><tr>
<td>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="Button1_Click" UseSubmitBehavior="true"/>
</td>
</tr>
<tr align="center">
<td>
<input id="Search1" value="one" type="radio" runat="server" name="sitesearch" />Site Name
<input id="Search2" value="two" type="radio" runat="server" name="sitesearch" />
<img src="http://www.google.com/images/poweredby_transparent/poweredby_FFFFFF.gif" alt="Google" />
</td>
</tr>
</table>
and then i have...
protected void Button1_Click(object sender, EventArgs e){
if (Search1.Checked)
{
//My Search
Response.Redirect(Request.UrlReferrer.AbsolutePath +...
}
else if (Search2.Checked)
{
//Google search
btnSearch.Attributes.Add("OnClick", "window.open('http://www.google.com/search?q=" + Regex.Replace(TextB.Text, " ", "+") + "','_blank');");
}
}
...and i have this...
TextBox TextB;
HtmlInputRadioButton radioBSite;
Button btnSearch;
HtmlInputRadioButton radioBGoogle;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
TextB = (TextBox)FindControl("TextBox1");
TextB.Text = Request["find"];
radioBSite = (HtmlInputRadioButton)FindControl("Search1");
radioBSite.Checked = true;
radioBGoogle = (HtmlInputRadioButton)FindControl("Search2");
btnSearch = (Button)FindControl("btnSearch");
btnSearch.Click += new EventHandler(Button1_Click);
.
.
}
The problem is with this line of code:
btnSearch.Attributes.Add("OnClick", "window.open('http://www.google.com/search?q=" + Regex.Replace(TextB.Text, " ", "+") + "','_blank');");
You are adding a client side OnClick, that will open the search in a new window (the _blank target).
If you do a:
Response.Redirect("http://www.google.com/search?q=" + TextB.Text);
Things will work as you expect.
instead of input controls use asp:RadioButton with autopost property as true and create and assign their events at design time
EDIT: Updated the code to open the search window.
The following may help you. It's not performing a search, but you should be able to get the general idea.
ASPX:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<div>
<asp:TextBox ID="SearchFor" runat="server"></asp:TextBox><br />
<asp:RadioButton ID="RadioGoogle" runat="server" GroupName="SearchSelect" Text="Google" />
<asp:RadioButton ID="RadioCustom" runat="server" GroupName="SearchSelect" Text="Custom" /><br />
<asp:Button ID="Search" runat="server" onclick="Search_Click" Text="Search" />
</div>
</form>
Codebehind:
protected void Search_Click(object sender, EventArgs e)
{
if (RadioGoogle.Checked)
GoogleSearch(SearchFor.Text);
if (RadioCustom.Checked)
Response.Write("Search Custom for " + SearchFor.Text);
}
private void GoogleSearch(string searchFor)
{
string targetURL = "http://www.google.com/search?q=" + Regex.Replace(searchFor, " ", "+");
string clientScript = "window.open('" + targetURL + "');";
ClientScript.RegisterStartupScript(GetType(), "popup", clientScript, true);
}
Swap the Response.Write's for a call to a method that does your search.

Categories