Can't get modified value from textbox in gridview - c#

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.

Related

Textbox not getting readonly

I have a textbox, on click, it allows you to select date from calendar control. If the date is deleted, it should uncheck the checkbox available just next to the textbox.
With below code, I am able to achieve everything other than making the textbox readonly so that user is not able to type anything. Also, once the text is selected, checkbox gets checked but when text is deleted the checkbox doesn't get unchecked.
Can anyone suggest what needs I might be doing wrong here ?
<asp:CalendarExtender ID="CalForDate" runat="server" TargetControlID="txtDate" Format="MM/dd/yyyy" PopupPosition="BottomLeft" DefaultView="Days"></asp:CalendarExtender>
<asp:TextBox runat="server" ID="txtDate" AutoPostBack="true" EnableViewState = "false" onKeyPress="javascript:return ChkCheckBox()" OnTextChanged="txtDate_OnTextChanged"></asp:TextBox>
The javascript code:
function ChkCheckBox() {
var txtDate = document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_txtDate').value;
if (txtDate.length == 9) {
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = true;
}
else
{
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = false;
}
In pageload I have added:
if (!IsPostBack){
txtDate.Attributes.Add("readonly", "readonly");}
And on text changed:
public void txtDate_OnTextChanged(object o, EventArgs e){
if (!(string.IsNullOrEmpty(txtDate.Text)))
{
chkDate.Visible = true;
chkDate.Checked = true;
}
else
{
chkDate.Visible = true;
chkDate.Checked = false;
} }
You can easily achieve this using jquery. I am sending you the sample code. Please don't hesitate to ask further assistance if needed.
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').on('change', function () {
//console.log('Tested');
if ($(this).val().toString().trim() != '') {
$('[Id*=ckTest]').attr('checked', 'checked');
}
else {
$('[Id*=ckTest]').removeAttr('checked');
}
});
$('#btnClear').click(function () {
$('#txtDate').val('');
$('#txtDate').trigger('change');
});
});
</script>
The code file is as below.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" ClientIDMode="Static"></asp:TextBox>
<asp:CheckBox ID="ckTest" runat="server" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" />
<button id="btnClear">Clear</button>
</div>
</form>
Just add jquery to project i used
jquery-2.1.4.min.js

Get multiline textbox value from jquery dialog

I try to make a popup dialog in my asp net website with form for send message.
I do in asp net user control:
<asp:Panel runat="server" ID="panelMain" ToolTip="" style="display: none">
<asp:Label runat="server" ID="Label1" AssociatedControlID="txtMessage" Text=""></asp:Label>:
<br />
<asp:TextBox runat="server" ID="txtMessage" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
ControlToValidate="txtMessage" Display="Dynamic"
ErrorMessage=""></asp:RequiredFieldValidator>
<br />
<asp:Button ID="butOk" runat="server" Text="" OnClick="butOk_Click"/>
<asp:Button ID="butCancel" runat="server" Text="" CausesValidation="false" />
</asp:Panel>
<script type="text/javascript">
$(document).ready(function()
{
$(".lbPopupLink").click(function() { //click hyperlink form main page
$("#<%= this.panelMain.ClientID %>").css("display", "block");
$("#<%= this.panelMain.ClientID %>").dialog
({
autoOpen: false,
modal: true,
width: 400,
height: 300,
dialogClass: "popupDialog",
resizable: false,
overlay: { opacity: 0.5, background: "black" },
}).dialog("open");
return false;
});
$("#<%= this.butCancel.ClientID %>").click(function()
{
$("#<%= this.panelMain.ClientID %>").dialog("close");
return false;
});
$("#<%= this.butOk.ClientID %>").click(function()
{
return $("#<%= this.panelMain.ClientID %>").dialogCloseAndSubmit($(this).attr("id"));
});
});
</script>
$.fn.extend({
dialogCloseAndSubmit: function(butOkId)
{
var dlg = $(this).clone();
$(this).dialog("destroy").remove();
dlg.css("display", "none");
$("form:first").append(dlg);
$("#" + butOkId, dlg).click();
return true;
}
});
In code behind:
protected void butOk_Click(object sender, EventArgs e)
{
// will be send mail
Literal str_message = new Literal();
str_message.Mode = LiteralMode.PassThrough;
str_message.Text = "<br />Success!Message: " + this.txtMessage.Text;
this.Page.Controls.Add(str_message);
}
And it's all good when TextBox is one line (Success!Message: hello), but if I change attribute to TextMode="MultiLine" I have no TextBox value (Success!Message:)
How can I solve this problem?
Maybe Try:
$(this).find('textarea[id*=txtMessage]').val();
As discussed in this answer

TextChanged event does not fire when 2nd modification equals the original value

I have a _TextChanged event which works properly except in a specific circumstance which can be replicated as follows:
User modifies text (event fires correctly)
User modifies text again to match the original value (event doesn't fire)
I can get the _TextChanged event to work on my development box by turning on Viewstate for the update panel on the ascx page, but when I move it to the server I get an error that the viewstate failed if I switch user controls and then switch back to that page. The controls which go inside the update panel are build dynamically in code behind and are rebuilt with each postback -- this works for every other postback so I don't think the issue is with the controls.
Additionally, turning on viewstate makes the page run dreadfully slow anyway, so this would not be an ideal fix.
Finally, the _TextChanged event works for all changes except when reverting back to the original value.
Can anyone tell me why the event doesn't fire in that specific circumstance, and how to address the problem?
Text box creation in code behind:
TextBox annualHoursTextBox = new TextBox();
annualHoursTextBox.ID = string.Format("bundle{0}_annualHoursTextBox{1}", bundle.BundleNbr, parentItem.LaborItemNbr);
annualHoursTextBox.CssClass = "";
annualHoursTextBox.Columns = 4;
annualHoursTextBox.Text = childItem == null ? string.Empty : childItem.FTEHours.ToString("F0");
annualHoursTextBox.AutoPostBack = true;
annualHoursTextBox.TextChanged += new EventHandler(annualHoursTextBox_TextChanged);
AsyncPostBackTrigger AHtrigger = new AsyncPostBackTrigger();
AHtrigger.ControlID = annualHoursTextBox.UniqueID;
AHtrigger.EventName = "TextChanged";
upPricingSheet.Triggers.Add(AHtrigger);
//snip
//add some attributes for reference on the events
annualHoursTextBox.Attributes["othercontrol"] = tasksPerYearTextBox.UniqueID;
annualHoursTextBox.Attributes["nextcontrol"] = benefitsTextBox.UniqueID;
annualHoursTextBox.Attributes["targetTBcontrol"] = taskTimeTextBox.UniqueID;
annualHoursTextBox.Attributes["targetDDLcontrol"] = taskTimeUOMDropDown.UniqueID;
Event Handler:
protected void annualHoursTextBox_TextChanged(object sender, EventArgs e)
{
TextBox ah = sender as TextBox;
TextBox other = Page.FindControl(ah.Attributes["othercontrol"]) as TextBox;
if ((!String.IsNullOrEmpty(ah.Text)) && (!String.IsNullOrEmpty(other.Text)))
{
TextBox next = Page.FindControl(ah.Attributes["nextcontrol"]) as TextBox;
TextBox targetTB = Page.FindControl(ah.Attributes["targetTBcontrol"]) as TextBox;
DropDownList ddl = Page.FindControl(ah.Attributes["targetDDLcontrol"]) as DropDownList;
Double TasksPerSecond;
TasksPerSecond = CalculateTimePerTask(ah.Text, other.Text);
string TimeUnit;
double Time;
if (TasksPerSecond < 60)
{
TimeUnit = "Seconds";
Time = TasksPerSecond;
}
else if (TasksPerSecond < 3600)
{
TimeUnit = "Minutes";
Time = (TasksPerSecond / 60);
}
else
{
TimeUnit = "Hours";
Time = (TasksPerSecond / 60 / 60);
}
//Enter the time in the appropriate textbox
targetTB.Text = Time.ToString("F2");
//select the appropriate item from the ddl
ListItem i = ddl.Items.FindByText(TimeUnit);
if (i != null)
{
ddl.SelectedItem.Selected = false;
i.Selected = true;
}
}
}
ASPX Page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Solution.aspx.cs" Inherits="Solution" %>
<%# Register Src="fragments/solutionRecommended.ascx" TagName="solutionRecommended"
TagPrefix="uc1" %>
<%# Register Src="fragments/solutionPricingSheet.ascx" TagName="solutionPricingSheet"
TagPrefix="uc2" %>
<%# Register Src="fragments/solutionSuggested.ascx" TagName="solutionSuggested" TagPrefix="uc3" %>
<%# Register Src="fragments/solutionSummary.ascx" TagName="solutionSummary" TagPrefix="uc4" %>
<%# Register Src="fragments/ucItemFilterSearch.ascx" TagName="ucItemFilterSearch"
TagPrefix="uc5" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script type="text/javascript">
function addItemToBundle(postUrl, redirectUrl) {
$.post(postUrl);
window.location = redirectUrl;
// window.location = url;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:HiddenField ID="hfStepNbr" runat="server" />
<asp:Panel ID="pnlStepMessage" runat="server" Visible="false" CssClass="padding10">
<h3 class="placeholder">
<asp:Label ID="lblMessage" runat="server" /></h3>
</asp:Panel>
<div class='elev8form' id="mainDiv" runat="server">
<h3 class='header'>
Solutions</h3>
<div id="tabs">
<div class='tab'>
<asp:LinkButton ID="lbSuggested" runat="server" Text="Select Items" data-step="1"
OnClick="lbTab_Click" CausesValidation="false"></asp:LinkButton>
</div>
<div class='tab'>
<asp:LinkButton ID="lbPricing" runat="server" Text="Pricing Worksheet" data-step="2"
OnClick="lbTab_Click" ></asp:LinkButton>
</div>
<div class='tab'>
<asp:LinkButton ID="lbRecommendedSolutions" runat="server" Text="Recommended Solutions"
data-step="3" OnClick="lbTab_Click" CausesValidation="false"></asp:LinkButton>
</div>
<div class='tab'>
<asp:LinkButton ID="lbSummary" runat="server" Text="Solutions Summary" data-step="4"
OnClick="lbTab_Click" CausesValidation="false"></asp:LinkButton>
</div>
</div>
<div id="solutions-body">
<asp:MultiView ID="mltSolution" runat="server">
<asp:View ID="viewSuggested" runat="server">
<uc3:solutionSuggested ID="solutionSuggested1" runat="server" RedirectUrl="~/portal/elev8/solution.aspx" />
</asp:View>
<asp:View ID="viewPricing" runat="server">
<uc2:solutionPricingSheet ID="solutionPricingSheet1" runat="server" />
</asp:View>
<asp:View ID="viewRecommended" runat="server">
<uc1:solutionRecommended ID="solutionRecommended1" runat="server" />
</asp:View>
<asp:View ID="viewSummary" runat="server">
<p style="font-size: 14px;">
Text here
</p>
<uc4:solutionSummary ID="solutionSummary1" runat="server" />
</asp:View>
</asp:MultiView>
</div>
</div>
<script type="text/javascript">
function pageLoad() {
$(function () {
var maxChannelHeight;
var items = $('.channel');
for (var counter = 0; counter < items.length; counter++) {
var channel = items[counter];
var channelHeight = $(channel).height();
maxChannelHeight = maxChannelHeight > channelHeight ? maxChannelHeight : channelHeight;
}
$('.channel').height(maxChannelHeight);
$("#priceing-sheet-save-button *").click(function () {
window.scrollTo(0, 0);
});
});
}
</script>
ASCX Page:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="solutionPricingSheet.ascx.cs"
Inherits="solutionPricingSheet" %>
<asp:UpdateProgress ID="upProgressRecSolution" runat='server' AssociatedUpdatePanelID="upPricingSheet">
<ProgressTemplate>
<div style="position: absolute; z-index: 2000; left: 45%; display: inline; width: 100px;"
class="elev8form">
<asp:Image ID="Image1" runat='server' ImageUrl="~/portal/img/ajax-loader-big.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<div id="pricing-sheet-wrapper">
<p class='left'>
More text</p>
<asp:Panel ID="pnlSaveMessage" runat="server" Visible="false" CssClass="save-message">
<span>Item prices saved</span>
</asp:Panel>
<div class='export'>
<span class='bigbutton'>
<asp:LinkButton ID="btnExport" runat='server' Text="Export to Excel" OnClick="btnExport_Click" />
</span>
</div>
<asp:UpdatePanel ID="upPricingSheet" runat="server" UpdateMode="Conditional" ViewStateMode="Disabled">
<ContentTemplate>
<div id="pricing-sheet">
<asp:PlaceHolder ID="phContent" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="opportunityPlaceHolder" runat="server" />
<div class='save export'>
<div>
<div id="pageValidationError" class="validationMessage">
* Changes not saved. Review all entries for validation messages. Required fields marked with an asterisk.
</div>
</div>
<%--<asp:HiddenField ID="hf" runat="server" value="0" />--%>
<center>
<span id="priceing-sheet-save-button">
<asp:Button ID="btnSave" runat="server" Text="Save All Prices" SkinID="redbutton"
OnClick="btnSave_Click" CausesValidation="true" />
</span>
</center>
</div>
</div>
<script type="text/javascript">
function pageLoad() {
$("#tabs .tab a").click(function () {
$("#<%= btnSave.ClientID%>").click();
});
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.validationMessage').hide();
$('#<%= btnSave.ClientID %>').click(function () {
if (Page_IsValid == false) {
$('.validationMessage').show();
return false;
}
});
$('input[type=text]').blur(function () {
if (Page_IsValid == false) {
$('.validationMessage').show();
return false;
}
else {
$('.validationMessage').hide();
}
})
});
That is the intended behavior - the event is called OnTextChanged (different from original) not OnTextTyped (any text entered), for that you would have to handle this event (which triggers even if nothing at all is entered):
OnBlur="__doPostBack(this.id, '');"
UPDATE: its pretty simple actually, since you are using ajax, your textbox's .defaultValue is not changing between postbacks, only the .value is - so either use OnBlur as I told you, or on every postback change the .defaultValue to .value in javascript: http://www.w3schools.com/jsref/prop_text_defaultvalue.asp
or just place the textbox in the UpdatePanel, and it will take care of it self on its own...
UPDATE 2: First off, nowhere in your code is the textbox shown to be inside an `UpdatePanel', and secondly, you have 3 choices:
a) For OnBlur method to work, remove AutoPostBack property (it is the client side OnChange event), but keep the OnTextChanged event (it is server side).
b) For ViewState method to work, set ViewStateMode="Enabled" on the textbox, and make sure you are using ViewStateMode="Disabled" on its containers - and not EnableViewState="False".
c) javascript .defaultValue method...

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,

Recaptcha in Updatepanel disappears during PostBack

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>

Categories