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.
Related
I'm having trouble trying to clear these banking and routing numbers that are in a textbox on an aspx page. I've seen it used where they would just specify the ID of the textbox and do a textbox.text = String.Empty(). But that doesn't seem to work here. Maybe I'm using the wrong ID?? I also tried using JQuery .val("") but that didn't seem to work either.
Here's the code, i'd like to clear both Routing and Account text fields on click of a button:
<div id="DivUser1BankInfo" class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelRoutingNumber" runat="server" Text="Routing #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextRoutingNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankRoutingNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelAccountNumber" runat="server" Text="Account #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextAccountNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankAccountNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<button type="button" id="clearButton1">Clear</button>
<div class="button">
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' OnClick="clearFields_btn"/><br />
</div>
The OnClick= "clearFields_btn" code behind =
protected void clearFields_btn(object sender, EventArgs e)
{
}
Thanks for any help!
I haven't worked with ASP.NET in a little while, but I think you may want the OnClientClick event, not OnClick. OnClientClick is for client-side code (your jQuery/JavaScript) and OnClick is for server-side code (your C# or VB.NET).
You'd also want your OnClientClick event method to return false, or the server-side code will also fire.
So I think you want something like:
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>
OnClientClick="clearText();"/>
And then clearText would look like this:
<script>
function clearText()
{
//our two IDs
$('input[id*="User1TextRoutingNumber"]').each(function(index) {
$(this).val('');
});
$('input[id*="User1TextAccountNumber"]').each(function(index) {
$(this).val('');
});
return false;
}
</script>
EDIT: shoot, I see my mistake. Fixed the code to clear the text of the textbox, not the button ("this").
Edit: removed the space from the "clear" text val.
EDIT: Made search a little more flexible, less dependent on GridView or no GridView.
Try this
<script>
var clear = function(textboxID){$('input[id*=' + textboxID + ']').val('');};
return false;
</script>
<button id="btClearText" onclick="javascript:return clear('txtName');">
but if you need a more specific answer then please post more information
You need something like this. Assuming you want a client side solution (not very clear from your question).
<script type="text/javascript">
function clearTextBox() {
document.getElementById("<%= User1TextRoutingNumber.ClientID %>").value = "";
//or
$("#<%= User1TextRoutingNumber.ClientID %>").val("");
}
</script>
The <%= User1TextRoutingNumber.ClientID %> will ensure you get the correct ID for javascript/jQuery.
A server side solution would be:
protected void clearFields_btn(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tb = GridView1.Rows[i].FindControl("User1TextAccountNumber") as TextBox;
tb.Text = "";
}
}
I'm new to ASP.NET and C#, I tried few things but did not worked. I have an .aspx page where I have three buttons, as shown in below code:
<body>
<form id="htmlForm" runat="server">
<telerik:RadScriptManager ID="rsm" AsyncPostBackTimeout="1800" runat="server" />
<telerik:RadAjaxPanel ID="rap" runat="server" LoadingPanelID="ralp">
<table>
<tr>
<td colspan="2">
Invoice Download
</td>
</tr>
<tr>
<td>
Invoice Start #
</td>
<td>
<telerik:RadNumericTextBox ID="rntbStart" Runat="server" MaxValue="1000000" MinValue="1000" Width="75px" >
<NumberFormat DecimalDigits="0" GroupSeparator="" />
</telerik:RadNumericTextBox>
</td>
</tr>
<tr>
<td>
Invoice End #
</td>
<td>
<telerik:RadNumericTextBox ID="rntbEnd" Runat="server" MaxValue="1000000" MinValue="1000" Width="75px" >
<NumberFormat DecimalDigits="0" GroupSeparator="" />
</telerik:RadNumericTextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="cmdDownload" runat="server" Text="Download" />
<asp:Button ID="cmdDownloadSAP" runat="server" Text="Download SAP" />
</td>
</tr>
</table>
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</telerik:RadAjaxPanel>
<telerik:RadAjaxLoadingPanel ID="ralp" Runat="server" Skin="Default" />
<asp:Button ID="btnConform" Visible="false" runat="server" Text="Conform Download" OnClick="btnConform_Click" />
</form>
I'm trying to do that btnConform will be initially invisible while the page is loading and now if I click cmdDownload or cmdDownloadSAP, button btnConform must get visible. Now if I click again on btnConform it will become invisible.
I cannot use JavaScript because cmdDownload and cmdDownloadSAP have some other task to complete before I make btnConform visible (say database call) and the btnConform will become visible only if the database call is successful.
partial class XPO_Accounting_InvoiceDownload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdDownload_Click(object sender, System.EventArgs e)
{
Session["InvoiceStart"] = rntbStart.Value;
Session["InvoiceEnd"] = rntbEnd.Value;
try
{
//All DB call
btnConform.Visible = true;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
protected void cmdDownload0_Click(object sender, System.EventArgs e)
{
Session["InvoiceStart"] = rntbStart.Value;
Session["InvoiceEnd"] = rntbEnd.Value;
try
{
//All DB call
btnConform.Visible = true;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
cmdDownload.Click += cmdDownload_Click;
cmdDownloadSAP.Click += cmdDownload0_Click;
}
protected void btnConform_Click(object sender, EventArgs e)
{
double InvoiceStart = (double)Session["InvoiceStart"];
double InvoiceEnd = (double)Session["InvoiceEnd"];
try
{
SqlHelper.ExecuteNonQuery(XPOStaticData.Instance.SQL, CommandType.Text, "update tblInvoiceNum set uploadedtoacct = 'Y' WHERE Status='I' AND InvoiceNum BETWEEN " + InvoiceStart + " AND " + InvoiceEnd + " and uploadedtoacct = 'N'");
lblResult.Text = "Downloaded Invoiced has conformed as the correct one.";
btnConform.Visible = false;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
}
This does not work.
Sorry for change the content of the question (cause older content wasn't pointing the problem properly). This is actual code here I'm trying to do it. (it looks stupid to pest the complete code...)
Add the Visible property to the Button using markup to initially set the second button's visibility:
<asp:Button ID="btnOne" runat="server" Text="One" OnClick="btnOne_Click" />
<asp:Button ID="btnTwo" runat="server" Visible="False" Text="Two" OnClick="btnTwo_Click" />
And on the event handlers, add this:
protected void btnOne_Click(object sender, EventArgs e)
{
btnTwo.Visible = true;
}
protected void btnTwo_Click(object sender, EventArgs e)
{
btnTwo.Visible = false;
}
You change visibility with the Visible property:
protected void btnOne_Click(object sender, EventArgs e)
{
//require code to make it visible
btnTwo.Visible = true;
}
protected void btnTwo_Click(object sender, EventArgs e)
{
//require code to make it invisible
btnTwo.Visible = false;
}
If you want to make a server control initially invisible you also have to use this property, so you can either use codebehind to change visibility programmatically ore declaratively on the aspx-page:
<asp:Button ID="btnTwo" Visible="false" runat="server" Text="Two" OnClick="btnTwo_Click" />
One final note, Visible=false on serverside means that this control is not rendered at all on client-side. So it does simply not exist and can not be accessed (or made visible) on client-side.
If you need to access it on client-side you should make it invisible via stylesheets either by using
display: none(does not take up any space) or
visibility: hidden(still takes up space in the layout).
Update acc. to the last edit of your question the event handlers don't seem to be registered anymore.
So you need:
<asp:Button ID="cmdDownload" OnClick="cmdDownload_Click" runat="server" Text="Download" />
<asp:Button ID="cmdDownloadSAP" OnClick="cmdDownload0_Click" runat="server" Text="Download SAP" />
Okay, i think i've tried 3-4 methods here from stackoverflow, but none seems to work.
I've got:
OnClientClick='<%# Eval("albumName", "doConfirm(\"delete\", \"{0}\");").ToString() %>'
but in html it renders as:
onclick="doConfirm("delete", "Test");"
Also tried making a method to call:
public string CreateConfirmation(String action, String item) {
return String.Format(#"return confirm('Sikker på du vil {0}: {1}');", action, item);
}
With this:
OnClientClick='<%# CreateConfirmation("delete", (string)Eval(albumName)) %>'
But gives me exact same problem....
So im pretty lost?
I apologize in advance for such a long answer, but I wanted to be thorough.
This is apparently a "security" feature in .Net 4.0 (and higher). You can read more about it at:
http://avinashsing.sunkur.com/2010/10/29/asp-net-html-encoding-attributes-in-server-controls/
http://forums.asp.net/p/1554455/3818604.aspx
Stop the tag builder escaping single quotes ASP.NET MVC 2
All of the above links also recommend declaring a public class to override the behavior:
public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
{
protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
{
output.Write(value);
}
}
and then adding this to the <system.web> element in your web.config:
<httpRuntime encoderType="HtmlAttributeNoEncoding"/>
This definitely fixes the rendering problem, so that quotes and apostrophes render as " and ' (as expected).
That said, I tested your problem with the following:
<script type="text/javascript">
var doConfirm = function (action, item) {
alert('Sikker på du vil ' + action + ': ' + item);
return false;
};
</script>
<p>Some "arbitrary" text. <asp:Button ID="Button3" runat="server" Text="Button" OnClientClick="doConfirm('delete', 'myalbum');" /></p>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick='<%# Eval("albumName", "doConfirm(\"delete\", \"{0}\");").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Album Name" DataField="albumName" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Button" OnClientClick='<%# CreateConfirmation("delete", (string)Eval("albumName")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in the code-behind:
public partial class _Default : System.Web.UI.Page
{
public string CreateConfirmation(String action, String item)
{
return String.Format(#"return doConfirm('{0}', '{1}');", action, item);
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("albumName", typeof(string));
DataRow dr = null;
dt.Columns.Add(dc);
dr = dt.NewRow();
dr["albumName"] = "Zen Arcade";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["albumName"] = "New Day Rising";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["albumName"] = "Candy Apple Grey";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
I was able to duplicate your rendering problem:
<p>Some "arbitrary" text.
<input type="submit" onclick="doConfirm('delete', 'myalbum');" value="Button" name="ctl00$MainContent$Button3" id="MainContent_Button3" />
</p>
<div>
<table cellspacing="0" rules="all" border="1" id="MainContent_GridView1"
style="border-collapse:collapse;">
<tr>
<th scope="col"> </th>
<th scope="col">Album Name</th>
<th scope="col"> </th>
<th scope="col">albumName</th>
</tr>
<tr>
<td>
<input type="submit" onclick="doConfirm("delete", "Zen Arcade");" value="Button" name="ctl00$MainContent$GridView1$ctl02$Button1" id="MainContent_GridView1_Button1_0" />
</td>
<td>Zen Arcade</td>
<td>
<input type="submit" onclick="return doConfirm('delete', 'Zen Arcade');" value="Button" name="ctl00$MainContent$GridView1$ctl02$Button2" id="MainContent_GridView1_Button2_0" />
</td>
<td>Zen Arcade</td>
</tr>
<tr>
<td>
<input type="submit" onclick="doConfirm("delete", "New Day Rising");" value="Button" name="ctl00$MainContent$GridView1$ctl03$Button1" id="MainContent_GridView1_Button1_1" />
</td>
<td>New Day Rising</td>
<td>
<input type="submit" onclick="return doConfirm('delete', 'New Day Rising');" value="Button" name="ctl00$MainContent$GridView1$ctl03$Button2" id="MainContent_GridView1_Button2_1" />
</td>
<td>New Day Rising</td>
</tr>
<tr>
<td>
<input type="submit" onclick="doConfirm("delete", "Candy Apple Grey");" value="Button" name="ctl00$MainContent$GridView1$ctl04$Button1" id="MainContent_GridView1_Button1_2" />
</td>
<td>Candy Apple Grey</td>
<td>
<input type="submit" onclick="return doConfirm('delete', 'Candy Apple Grey');" value="Button" name="ctl00$MainContent$GridView1$ctl04$Button2" id="MainContent_GridView1_Button2_2" />
</td>
<td>Candy Apple Grey</td>
</tr>
</table>
</div>
When any of the buttons were clicked, the JavaScript function ignored the HTML encoding, alerting me to:
Sikker på du vil delete: Zen Arcade
so while it looks funky in the source, having quotes and apostrophes render as " and ' doesn't really appear to affect anything.
Try the following:
<asp:Button OnClientClick="Delete(this);" Text='<%# Eval("albumName"); %>' />
JS:
function Delete(element) {
var value = element.value;
return confirm('Delete' + value + '?');
}
Just attach the event server side inside rowDataBound event like, (you can replace linkbutton with Button)
LinkButton myLinkButton=(LinkButton)e.row.FindControl("yourButtonName");
if(myLinkButton!=null)
{
myLinkButton.Attributes.Add("onclick","javascript:return confirm ('Are you sure you want to delete "+ DataBinder.Eval(e.row.DataItem, "YourDbField") + " ?');");
}
Even though this question is 5 years old, I wanted to follow up as I had the same issue with an ImageButton and was able to resolve it using a HiddenField.
Background: I have a Web User Control which I wanted to have a help button displayed if there was help available.
I added a HiddenField and an ImageButton to the User Control. I then created a property on the control so the developer may add help text.
ASPX Page
<asp:HiddenField ID="hidHelpText" runat="server" />
<asp:ImageButton ID="imgHelp" runat="server" ImageUrl="~/images/help.png" Visible="False" />
Code Behind (CS File)
public string HelpText
{
get { return hidHelpText.Value; }
set { hidHelpText.Value = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
imgHelp.Visible = !string.IsNullOrEmpty(HelpText);
imgHelp.OnClientClick = string.Format("MsgBox({0}.value, MessageButtons.OK); return false;", hidHelpText.ClientID);
}
This gets around the issue as the text belongs to the hidden field instead of trying to include it within the JavaScript for the OnClientClick property.
BTW: I cannot copy and paste so this code may contain some typos but I believe it is correct. At least it points the way so you may be able to work around the issue.
I'm trying to code a page where you can post a comment without reloading the whole page. The comments are displayed using a Repeater control. The template looks like this:
<asp:UpdatePanel runat="server" ID="commentsUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<!-- Comments block -->
<div class="wrapper bloc content">
<h3><img src="img/comments.png" alt="Comments" /> Comments</h3>
<p><asp:Label ID="viewImageNoComments" runat="server" /></p>
<asp:Repeater ID="viewImageCommentsRepeater" runat="server">
<HeaderTemplate>
<div class="float_box marge wrapper comments">
</HeaderTemplate>
<ItemTemplate>
<div class="grid_25">
<span class="user"><%#Eval("username")%></span><br />
<span style="font-size:x-small; color:#666"><%#Eval("datetime") %></span>
</div>
<div class="grid_75">
<p align="justify"><%#Eval("com_text") %></p>
</div>
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
</div>
<!-- Post comment block -->
<div class="wrapper bloc content">
<h3><a id="post_comment" name="post_comment"><img src="img/comment_edit.png" alt="Comments" /></a> Post
a comment</h3>
<p class="description">Please be polite.</p>
<p>
<asp:Label ID="postCommentFeedback" runat="server" />
</p>
<table border="0">
<tr>
<td valign="top">
<asp:TextBox id="postCommentContent" runat="server" TextMode="MultiLine"
MaxLength="600" Columns="50" Rows="15" Width="400px" />
</td>
<td valign="top">
<span style="font-size:x-small">BBCode is enabled. Usage :<br />
<b>bold</b> : [b]bold[/b]<br />
<i>italic</i> : [i]italic[/i]<br />
<span class="style1">underline</span> : [u]underline[/u]<br />
Link : [url=http://...]Link name[/url]<br />
Quote : [quote=username]blah blah blah[/quote]</span>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="postCommentButton" runat="server" Text="Submit"
onclick="postCommentButton_Click" />
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The postCommentButton_Click() function works just fine - clicking "Submit" will make the post. However, I need to completely reload the page in order to see new comments - the post the user just made will not show until then. I Databind the Repeater in Page_Load() after a (!isPostBack) check.
The postCommentButton_Click() function looks like this:
protected void postCommentButton_Click(object sender, EventArgs e)
{
// We check if user is authenticated
if (User.Identity.IsAuthenticated)
{
// Attempt to run query
if (Wb.Posts.DoPost(postCommentContent.Text, Request.QueryString["imageid"].ToString(), User.Identity.Name, Request.UserHostAddress))
{
postCommentFeedback.Text = "Your post was sucessful.";
postCommentContent.Text = "";
}
else
{
postCommentFeedback.Text = "There was a problem with your post.<br />";
}
}
// CAPTCHA handling if user is not authenticated
else
{
// CAPTCHA
}
}
In my case, we do see postCommentFeedback.Text refreshed, but, again, not the content of the repeater which should have one more post.
What is it I'm missing?
You should DataBind in the Page_Load within a !IsPostBack as you are. You should ALSO databind in your Click event.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.DataBind();
}
}
protected void MyButton_Click(object sender, EventArgs e)
{
//Code to do stuff here...
//Re DataBind
this.DataBind();
}
public override void DataBind()
{
//Databinding logic here
}
Instead of making your datasource a MySqlDataReader, have your reader populate a BindingList or something like that. Keep that in session and do your databind every non-postback and click. When your user posts, you can either add it to the list and wait for something to tell it to save that, but it makes more sense in the context of posting comments to save their post to your db and redo your datapull and stomp over your BindingList and re-Databind.
Also, personal peeve: I dislike <%#Eval....%>. Code in your page is usually a bad sign. Try using the Repeater.ItemDataBound Event
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx
It sounds to me like the quick fix is to bind on page load regardless of postback. Alternatively, you could rebind from within postCommentButton_Click.
protected void Timer1_Tick(object sender, EventArgs e)
{
Repeater1.DataBind();
/*This is all I did for it to work.*/
}
protected void Buttontextbox_Click(object sender, EventArgs e)
{
this.DataBind();
/*Leave sql connection to your database above "this.databind"*/
}
try putting the update panel between tags and if you have already done that then check if the closing of div tags is proper
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);
}
}