Recaptcha in Updatepanel disappears during PostBack - c#

I am using Google ReCaptcha V2 and it is inside an updatepanel. IF validation failed ReCaptcha disappears on postback.
I read similar topics but I have not yet found an answer that solves my problem.
Please help!
My ASPX code :
<%# Register Assembly="GoogleReCaptcha" Namespace="GoogleReCaptcha" TagPrefix="cc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<form id="formRegister" runat="server">
<asp:ScriptManager ID="ScriptManagerRegister" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanelRegister" hildrenAsTriggers="false" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="ButtonRegister" runat="server" Text="Registrera" CssClass="btn btn-primary btn-md" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</asp:Content>
My code behind C#
GoogleReCaptcha.GoogleReCaptcha ctrlGoogleReCaptcha = new GoogleReCaptcha.GoogleReCaptcha();
protected override void CreateChildControls()
{
base.CreateChildControls();
ctrlGoogleReCaptcha.PublicKey = "My Public Key";
ctrlGoogleReCaptcha.PrivateKey = "My Private Key";
this.Panel1.Controls.Add(ctrlGoogleReCaptcha);
}
protected void Page_Load(object sender, EventArgs e)
{
ButtonRegister.Click += new EventHandler(ButtonRegister_Click);
}
protected void ButtonRegister_Click(object sender, EventArgs e)
{
if (ctrlGoogleReCaptcha.Validate())
{
//submit form
Label1.Text = "Success";
}
else
{
Label1.Text = "Captcha Failed!! Please try again!!";
}
}

use this script after body
<body>
<script language="javascript" type="text/javascript">
function pageLoad()
{
$('.g-recaptcha').each(function (index, obj) {
grecaptcha.render(obj, { 'sitekey': 'yoursitekey' });
});
}
</script>

Related

ScriptManager.RegisterStartupScript not triggered second time inside updatepanel

My aspx page
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
My CS page
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
When I click the "Play" button for first time, OpenPlayerWindow() or OpenPlayerWindowForError() opens accoding to the condition. And if I click the button again, "btnPlay" is called but not any of JS function.
If I refresh the page, it works perfect again.
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</span>
I am not able to write this code in comments hence I am writing this as an answer. The following is the code which I have with me. Please copy-paste it in a separate project and try if it works.
Also if I am not replicating this issue properly(not written the code correctly) then please comment.
If the code is okay with you and if it works on a separate project then there probably is a problem in some other code which is not shown in your question.
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Practice_Web.WebForm2" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<%--It works if I keep the script here also--%>
</div>
</form>
</body>
<script type="text/javascript">
function OpenPlayerWindow() {
alert("Thanks!");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!");
}
</script>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practice_Web
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//This is just to simulate the condition part of the original code
if (Session["condition"] == null)
Session["condition"] = false;
else
Session["condition"] = !Convert.ToBoolean(Session["condition"]);
}
protected void btnPlay(object sender, EventArgs e)
{
bool condition = Convert.ToBoolean(Session["condition"]);
if (condition)
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
}
}
try below code
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(this, GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}

Can't get modified value from textbox in gridview

I'm trying to get gridview data using jquery. I have modified existing data on textbox and try to get that value using jquery. but it gave old value in textbox. not modified value in textbox.
ASPX Code
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
/*javascripts and stylesheets are here*/
<script type="text/javascript">
function Navigate() {
$('#dialogDiv').dialog('open');
}
$(document).ready(function () {
var list = "";
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$("#<%=Type_GV.ClientID %> tr").each(function () {
//Skip first(header) row
if (!this.rowIndex) return;
var type = $(this).find("td:last").html();
list += type + "</br>";
});
alert(list)
}
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="dialogDiv" title="Type" style="overflow: hidden">
<div id="TypeDiv" class="divTable">
<div class="divRow">
<div class="divColumn">
<div>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="open" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="Type_GV" runat="server" ShowFooter="True" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:TextBox ID="txtType" runat="server" Text='<%# Bind("Type") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="open" runat="server" Text="Open dialog" OnClientClick="Navigate()"
OnClick="open_Clicked" />
<br />
<p>
<asp:Button ID="btnSaveType" runat="server" OnClick="btnSaveType_Clicked" Style="visibility: hidden;
display: none;" />
</p>
</asp:Content>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void open_Clicked(object sender, EventArgs e)
{
VehicleType vTypeObject = new VehicleType();
Type_GV.DataSource = vTypeObject.GetTypeList();
Type_GV.DataBind();
}
protected void btnSaveType_Clicked(object sender, EventArgs e)
{
foreach (GridViewRow gvr in Type_GV.Rows)
{
TextBox type = (TextBox)gvr.FindControl("txtType");
Debug.WriteLine("type : " + type.Text);
}
}
public class VehicleType
{
public string Type { get; set; }
public List<VehicleType> GetTypeList()
{
List<VehicleType> list = new List<VehicleType>()
{
new VehicleType{Type="Type1"},
new VehicleType{Type="Type2"}
};
return list;
}
}
How can i solve this ?
You may use this:
As you are using the update panels, this.remove_endRequest() is raised after an asynchronous postback is finished and control has been returned to the browser.
Not sure but i think this the issue, i faced these kind of issues many times. Might be helpful to you.
See Documentation
Sys.WebForms.PageRequestManager.getInstance().remove_endRequest($(function(){
var list = "";
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$("#<%=Type_GV.ClientID %> tr").each(function () {
//Skip first(header) row
if (!this.rowIndex) return;
var type = $(this).find("td:last").html();
list += type + "</br>";
});
alert(list)
}
}
});
});)
Note: Don't remove $(document).ready(function{})) keep it as it is, and include this one.

iFrame in UpdatePanel not updating

I'm trying to update the source of an iFrame when a button is clicked on the page. However, nothing seems to be happening...
.ASPX:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
<asp:Button ID="ValidateButton" runat="server" Text="Validate" OnClick="SubmitSponsor" />
</p>
</div>
<iframe runat="server" id="PayPalFrame" height="150px" width="100%" frameborder="0"></iframe>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void SubmitSponsor(object sender, EventArgs e)
{
var driver = new Driver();
var isvalid = driver.IsAppValid(URL.Text, APILINK, Connstring);
if (isvalid)
{
PayPalFrame.Attributes.Add("src", "http://www.google.com");
URLInvalid.Visible = false;
}
}
I've also tried:
PayPalFrame.Attributes["src"] = "http://www.google.com"; and still nothing.
I have tested your code, and it works in a sample project:
ASPX:
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
<asp:Button ID="ValidateButton" runat="server" Text="Validate" OnClick="SubmitSponsor" />
</p>
</div>
<iframe runat="server" id="PayPalFrame" height="150px" width="100%" frameborder="0">
</iframe>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Codebehind:
public partial class UpdatePanelIFrameTester : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitSponsor(object sender, EventArgs e)
{
bool isvalid = true;
if (isvalid)
{
PayPalFrame.Attributes.Add("src", "http://www.ironworks.com");
}
}
}
I would inspect your code and ensure nothing is causing your page to refresh/perform a full postback (I changed the URL as google will not allow you to view it in an iframe under standard conditions).
I believe you have to remove the src attribute and then re-add it, for this to work. Not sure why this is, but I remember doing it the last time I worked with update panels. Perhaps it's because the src attribute always already exists?
Anyway, here's some sample code: how to change the src attribute in iframe.

updatepanel and javascript include file

I have found many solution for my issue but none doesn't work in my scenario.
I have created a test project to demo my concept.
Basically, there is a page that host a user control...
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
WebUserControl1 has a dropdownlist and two other webusercontrols (to be displayed based on the selection of dropdownlist element) inside updatepanel as below.
<%# Register Src="WebUserControl2.ascx" TagName="WebUserControl2" TagPrefix="uc2" %>
<%# Register Src="WebUserControl3.ascx" TagName="WebUserControl3" TagPrefix="uc3" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
<asp:Panel ID="pnlCreditCard" Visible="false" runat="server">
<uc2:WebUserControl2 ID="WebUserControl21" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlGiftCard" Visible="false" runat="server">
<uc3:WebUserControl3 ID="WebUserControl31" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind file for WebUserControl1 is .....
public enum PaymentMethod
{
CreditCard = 0,
GiftCard
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindPaymentMethods(Enum.GetValues(typeof(PaymentMethod)));
}
private void BindPaymentMethods(Array paymentMethods)
{
DropDownList1.DataSource = paymentMethods;
DropDownList1.DataBind();
if (paymentMethods.Length > 0)
{
DropDownList1.SelectedIndex = 0;
UpdateCreditOrGiftCardPanelVisibility();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateCreditOrGiftCardPanelVisibility();
}
private void UpdateCreditOrGiftCardPanelVisibility()
{
if(DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod),PaymentMethod.CreditCard))
{
pnlGiftCard.Visible = false;
pnlCreditCard.Visible = true;
}
else if (DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod), PaymentMethod.GiftCard))
{
pnlCreditCard.Visible = false;
pnlGiftCard.Visible = true;
}
}
Now, the problem starts here...There is an external javascript file [JScript1.js] (embedded resource) which basically is used to display an alert box.
<script language="javascript" type="text/javascript">
window.onload = function() {
alert('creditcard form');
}
WebUserControl2.ascx.cs code behind is
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType().BaseType, "JScript1", Page.ClientScript.GetWebResourceUrl(this.Page.GetType().BaseType, "WebApplication1.JScript1.js"));
}
Alert window doesn't get displayed when I change the dropdownlist value. Even the script is getting registered three times (look in the firebug)
Need to use ScriptInclude instead of ScriptBlock as the original JS file is too big.
Can email the test app....
Thanks in Advance
After working around a bit, I found the solution.
I registered a ScriptManagerProxy in WebUserControl2.ascx
<asp:ScriptManagerProxy ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Assembly="WebApplication1" Name="WebApplication1.JScript1.js" />
</Scripts>
</asp:ScriptManagerProxy>
Then on the code behind of the same control, added...
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this, GetType(), "test", "doSomething();", true);
}
and the JScript1.js file looks like below.
function doSomething() {
alert('via dosomething control2 form');
}
Hope that helps. Though I had to litter around more in my practical scenario but this was certainly the way I got it working.
Thanks,

Modify form action with javascript

I've got a multiple step webform written in c#/asp.net. I'm trying to change the url that posts back to for google analytics reasons. I've written the code below to change the url on the client side, but it doesn't seem to post to the url with the parameters on the end. Almost like it's being changed back on the client side onsubmit. Any ideas?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestNamespace.WebForm1" %>
<!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></title>
</head>
<body onload="setaction(<%= step %>);">
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCurrentUrl" runat="server"></asp:Label>
<asp:Panel ID="panel1" runat="server">
Panel 1<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Button" />
</asp:Panel>
<asp:Panel ID="panel2" runat="server" Visible="false">
Panel 2<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Button" />
</asp:Panel>
<asp:Panel ID="panel3" runat="server" Visible="false">
Panel 3<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="Button" />
</asp:Panel>
<asp:Panel ID="panel4" runat="server" Visible="false">
Panel 4<asp:Button ID="Button4" runat="server" onclick="Button4_Click"
Text="Button" />
</asp:Panel>
</div>
<script language="javascript" type="text/javascript">
function setaction(step) {
var bdy = document.getElementsByTagName("body")[0];
bdy.setAttribute("action", "webform1.aspx?step=" + step);
alert(document.location.href);
}
</script>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestNamespace
{
public partial class WebForm1 : System.Web.UI.Page
{
protected int step;
protected void Page_Load(object sender, EventArgs e)
{
lblCurrentUrl.Text = Request.Url.ToString();
if ( IsPostBack ) return;
step = 1;
}
protected void Button1_Click(object sender, EventArgs e)
{
panel1.Visible = false;
panel2.Visible = true;
step = 2;
}
protected void Button2_Click(object sender, EventArgs e)
{
panel2.Visible = false;
panel3.Visible = true;
step = 3;
}
protected void Button3_Click(object sender, EventArgs e)
{
panel3.Visible = false;
panel4.Visible = true;
step = 4;
}
protected void Button4_Click(object sender, EventArgs e)
{
}
}
}
It looks like you're setting the action on the body, rather than the form. Unless I'm missing something, you should be able to fix the problem like so:
function setaction(step) {
var frm = document.getElementsByTagName("form")[0];
frm.setAttribute("action", "webform1.aspx?step=" + step);
alert(document.location.href);
}

Categories