How can I validate google reCAPTCHA v2 using javascript/jQuery? - javascript

I have a simple contact form in aspx.
I want to validate the reCaptcha (client-side) before submitting the form.
Please help.
Sample code:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Form</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
$("#cmdSubmit").click(function () {
//need to validate the captcha
});
</script>
</head>
<body>
<form id="form1" runat="server">
<label class="clsLabe">First Name<sup>*</sup></label><br />
<input type="text" id="txtFName" name="txtFName" class="clsInput" /><br />
<div class="g-recaptcha" data-sitekey="my_key"></div>
<img id="cmdSubmit" src="SubmitBtn.png" alt="Submit Form" style="cursor:pointer;" />
</form>
</body>
</html>
I want to validate the captcha on cmdSubmit click.
Please help.

This Client side verification of reCaptcha - the following worked for me :
if reCaptcha is not validated on client side grecaptcha.getResponse(); returns null, else is returns a value other than null.
Javascript Code:
var response = grecaptcha.getResponse();
if(response.length == 0)
//reCaptcha not verified
else
//reCaptch verified

Use this to validate google captcha with simple javascript.
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this) method form button:
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}

If you render the Recaptcha on a callback
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
using an empty DIV as a placeholder
<div id='html_element'></div>
then you can specify an optional function call on a successful CAPTCHA response
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key',
'callback' : correctCaptcha
});
};
The recaptcha response will then be sent to the 'correctCaptcha' function.
var correctCaptcha = function(response) {
alert(response);
};
All of this was from the Google API notes :
Google Recaptcha v2 API Notes
I'm a bit unsure why you would want to do this. Normally you would send the g-recaptcha-response field along with your Private key to safely validate server-side. Unless you wanted to disable the submit button until the recaptcha was sucessful or such - in which case the above should work.
Hope this helps.
Paul

Simplified Paul's answer:
Source:
<script src="https://www.google.com/recaptcha/api.js"></script>
HTML:
<div class="g-recaptcha" data-sitekey="YOUR_KEY" data-callback="correctCaptcha"></div>
JS:
var correctCaptcha = function(response) {
alert(response);
};

I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script>
$("#contactForm").validate({
submitHandler: function (form) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if (response.length == 0) {
$('#recaptcha-error').show();
return false;
}
//recaptcha passed validation
else {
$('#recaptcha-error').hide();
return true;
}
}
});
</script>

I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>

Unfortunately, there's no way to validate the captcha on the client-side only (web browser), because the nature of captcha itself requires at least two actors (sides) to complete the process.
The client-side - asks a human to solve some puzzle, math equitation, text recognition, and the response is being encoded by an algorithm alongside with some metadata like captcha solving timestamp, pseudo-random challenge code.
Once the client-side submits the form with a captcha response code, the server-side needs to validate this captcha response code with a predefined set of rules, ie. if captcha solved within 5 min period, if the client's IP addresses are the same and so on.
This a very general description, how captchas works, every single implementation (like Google's ReCaptcha, some basic math equitation solving self-made captchas), but the only one thing is common - client-side (web browser) captures users' response and server-side (webserver) validates this response in order to know if the form submission was made by a human or a robot.
NB. The client (web browser) has an option to disable the execution of JavaScript code, which means that the proposed solutions are completely useless.

you can render your recaptcha using following code
<div id="recapchaWidget" class="g-recaptcha"></div>
<script type="text/javascript">
var widId = "";
var onloadCallback = function ()
{
widId = grecaptcha.render('recapchaWidget', {
'sitekey':'Your Site Key'
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Then you can validate your recaptcha by using "IsRecapchaValid()" method as follows.
<script type="text/javascript">
function IsRecapchaValid()
{
var res = grecaptcha.getResponse(widId);
if (res == "" || res == undefined || res.length == 0)
{
return false;
}
return true;
}
</script>

Source Link
You can simply check on client side using
grecaptcha.getResponse() method
var rcres = grecaptcha.getResponse();
if(rcres.length){
grecaptcha.reset();
showHideMsg("Form Submitted!","success");
}else{
showHideMsg("Please verify reCAPTCHA","error");
}

I used Palek's solution inside a Bootstrap validator and it works. I'd have added a comment to his but I don'y have the rep;). Simplified version:
$('#form').validator().on('submit', function (e) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if(response.length == 0) {
e.preventDefault();
$('#recaptcha-error').show();
}
//recaptcha passed validation
else {
$('#recaptcha-error').hide();
}
if (e.isDefaultPrevented()) {
return false;
} else {
return true;
}
});

Here's how we were able to validate the RECAPTCHA using .NET:
FRONT-END
<div id="rcaptcha" class="g-recaptcha" data-sitekey="[YOUR-KEY-GOES-HERE]" data-callback="onFepCaptchaSubmit"></div>
BACK-END:
public static bool IsCaptchaValid(HttpRequestBase requestBase)
{
var recaptchaResponse = requestBase.Form["g-recaptcha-response"];
if (string.IsNullOrEmpty(recaptchaResponse))
{
return false;
}
string postData = string.Format("secret={0}&response={1}&remoteip={2}", "[YOUR-KEY-GOES-HERE]", recaptchaResponse, requestBase.UserHostAddress);
byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = "";
using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
return System.Text.RegularExpressions.Regex.IsMatch(responseString, "\"success\"(\\s*?):(\\s*?)true", System.Text.RegularExpressions.RegexOptions.Compiled);
}
Call the above method within your Controller's POST action.

If you just want to avoid a trip to the server when the user hasn't even attempted the reCAPTCHA, put a validate function in the onsubmit action:
<form id="start_game" action="start-game" method="post" onsubmit="return validate_form();">
And then make that function something like this:
function validate_form() {
const recaptcha_box_checked = (grecaptcha.getResponse()) ? true : false;
if (recaptcha_box_checked) {
return true;
}
else {
alert("You must check the 'I am not a robot' box before you can start a game!");
return false;
}
}
Now, the user could certainly subvert this, but your backend is going to check the g-recaptcha-response with a google server using your secret key. This just stops the user from having to go through another page or two when she simply forgets to check the box.

You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.
let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
'callback': function(response) {
recaptchVerified = true;
// reCAPTCHA solved, allow signInWithPhoneNumber.
// ...
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.
So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.

if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {
dvcontainer = grecaptcha.render('dvCaptcha', {
'sitekey': ReCaptchSiteKey,
'expired-callback' :function (response){
recaptch.reset();
c_responce = null;
},
'callback': function (response) {
$("[id*=txtCaptcha]").val(c_responce);
$("[id*=rfvCaptcha]").hide();
c_responce = response;
}
});
}
function callonanybuttonClick(){
if (c_responce == null) {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
return false;
}
else {
$("[id*=txtCaptcha]").val(c_responce);
$("[id*=rfvCaptcha]").hide();
return true;
}
}
<div id="dvCaptcha" class="captchdiv"></div>
<asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
<label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
Captcha validation is required.

<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
function get_action() {
var v = grecaptcha.getResponse();
console.log("Resp" + v);
if (v == '') {
document.getElementById('captcha').innerHTML = "You can't leave Captcha Code empty";
return false;
}
else {
document.getElementById('captcha').innerHTML = "Captcha completed";
return true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="return get_action();">
<div>
<div class="g-recaptcha" data-sitekey="6LeKyT8UAAAAAKXlohEII1NafSXGYPnpC_F0-RBS"></div>
</div>
<%-- <input type="submit" value="Button" />--%>
<asp:Button ID="Button1" runat="server"
Text="Button" />
<div id="captcha"></div>
</form>
</body>
</html>
It will work as expected.

Related

Enter key as well as submit button on Google Script Code in Sheet

I would like to be able to use enter as well as the submit button to execute / accept data entry and commit to cell.
I cannot seem to get the code to work.
Any advice how to modify?
<script>
var itemBox = document.getElementById("itemname");
document.getElementById("btn").addEventListener("click",addRecord);
function addRecord(){
var name = itemBox.value;
if(name.trim().length == 0){
M.toast({html: "Please enter a valid barcode!"})
} else{
var data = {
name:itemBox.value
};
google.script.run.appendData(data);
itemBox.value = "";
}
}
</script>
Please read comments:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var itemBox = document.getElementById("itemname");
document.getElementById("btn").addEventListener("click",addRecord);
function addRecord(){
var name = itemBox.value;//item box is undefined
if(name.trim().length == 0){
M.toast({html: "Please enter a valid barcode!"})//M is undefined and toast does not exist clientside
} else{
var data = {name:itemBox.value};
google.script.run.appendData(data);
itemBox.value = "";
}
}
</script>
</body>
</html>
Spreadsheet.toast() is a server side method of Class Spreadsheet and is not intended to function clientside on the browser.
Spreadsheet.toast()
So far your description of your question is incomplete

Can't catch the value entered via form in another .jsp file. Why?

I have a form in index.jsp file, which allows to log into my app. I need to catch the inserted login to use it in another file called mainPage.jsp using Java code. When I do:
String login = request.getParameter("login");
this string has null value. How can I catch the inserted value?
Here is my code from index.jsp with forms resaponsible for logging into my app:
<body>
<form id="log" method="post" onsubmit="return check()" action="mainPage.jsp">
<div align="center">
Login: <input type="text" id="login" name="login"/>
<br/></br>
Password: <input type="password" id="password"/>
<br/></br>
<button name="login" type="submit">Log in!</button>
</div>
</form>
<script type="text/javascript">
function check() {
var login = document.getElementById("login").value;
var password = document.getElementById("password").value;
var flag = false;
var _users = JSON.parse(users);
for (var i = 0; i < _users.length; i++) {
if (_users[i].login == login && _users[i].password == password) {
flag = true;
}
}
if (flag == false) {
document.getElementById('info').innerHTML = "Wrong login or password!";
}
return flag;
}
</script>
</body>
First problem is in using wrong method:
HttpRequest.getParameter. This method finds parameter in URL. For example in this url
https://google.com/search?q=java
request.getParameter("q") returns java.
In your example you used POST query. It means that parameters will be in your request body in www-form-urlencoded format. Request will look like
login=login&password=password
The second problem is in using ids instead of names. To transfer params in tag you need to use names, not ids. Also button with name parameter will send empty input. After pressing button you will see next result on server
login=login&login=
And it's what we not expected. In example below I used names to send params correctly. If you need css style - use classes or id parameters instead of html tag name
To parse it without external libraries we have to
Parse request body
Extract parameters
Send response to client
Simple example of this:
login.jsp
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<style>
/* TODO: use classes of method to make styles */
label, input {
display: block;
}
</style>
</head>
<body>
<form method="post">
<label>Login:
<input type="text" name="login" />
</label>
<label>Password:
<input label="password" type="password" name="password"/>
</label>
<button type="submit">Log in!</button>
</form>
</body>
</html>
Servlet
#WebServlet(name = "login", value = "/login")
public class LoginServlet extends HttpServlet {
public static final String IS_AUTHENTICATED_PARAM = "isAuthenticated";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
this.getServletContext().getRequestDispatcher("/login.jsp").include(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Parse body
String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
//System.out.println(requestBody); - uncomment to view what is in body
String login = getParamFromBodyUrlEncoded(requestBody, "login");
String password = getParamFromBodyUrlEncoded(requestBody, "password");
//In future you can setup secret cookie and check it in other pages
if(login == null || password == null) {
request.setAttribute(IS_AUTHENTICATED_PARAM, false);
} else {
request.setAttribute("isAuthenticated", isCredentialsCorrect(login, password));
}
this.getServletContext().getRequestDispatcher("/loginResult.jsp").include(request, response);
}
private String getParamFromBodyUrlEncoded(String requestBody, String paramName) {
String paramUrlEncoded = paramName + "=";//param format is like login=. We expect paramname like login
//Search for param
int paramWithNameStart = requestBody.indexOf(paramUrlEncoded);
if(paramWithNameStart == -1) {
return null;
}
//Set pointer after param name
int paramStart = paramWithNameStart + paramUrlEncoded.length();
//Param should end with & or end of string
int paramEnd = requestBody.indexOf("&", paramStart);
if(paramEnd == -1) {
paramEnd = requestBody.length();
}
return requestBody.substring(paramStart, paramEnd);
}
private boolean isCredentialsCorrect(String login, String password) {
if("admin".equals(login) && "password".equals(password)) {
return true;
} else {
return false;
}
}
}
loginResult.jsp
<%# page import="com.example.demo_jsp.LoginServlet" %>
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Login result</title>
</head>
<body>
<h1><%=(boolean)request.getAttribute(LoginServlet.IS_AUTHENTICATED_PARAM) ?
"Success authentication" : "Wrong login or password"%></h1>
</body>
</html>
So, I finally managed to do this in a quite simple way.
When I log in, I store login name in session and then extract it later in my program.
I do this by calling this part of code after logging into my app:
if (request.getParameter("login") != null) {
session.setAttribute("_login", request.getParameter("login"));
}
And then, I catch the name of the logged person by:
String login = session.getAttribute("_login").toString();
It works pretty well! :-D

No transaction response when showReceipt is set to false in Accept Hosted approach (Authorize.net)

I'm trying to integrate authorize.net accept hosted page using the iframe approach in SAP Hybris. The iframe is supposed to send back a response when the showReceipt is set to false according to the documentation. But as of now it seems to be stuck after pay button is clicked.
I have been trying the approach in the documentation. Then tried out the solution in How to implement Authorize.NET Hosted Payments iFrame & Laravel .
This is the hostedOrderPage which is where the iframe displays:
<script type="text/javascript">
$(document).ready(function(){
window.CommunicationHandler = {};
function parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
vars[pair[0]] = unescape(pair[1]);
}
return vars;
}
window.CommunicationHandler.onReceiveCommunication = function (argument) {
console.log('communication handler enter');
var params = parseQueryString(argument.qstr)
switch(params['action']){
case "cancel" :
console.log('cancel'); break;
case "transactResponse" :
console.log("transaction response received");
console.log(transResponse.totalAmount);
}
}
//send the token
$('#send_hptoken').submit();
});
</script>
<div id="item_container_holder">
<div class="item_container">
<div id="iframe_holder" class="center-block" style="width:90%;max-width: 1000px" data-mediator="payment-form-loader">
<iframe id="load_payment" class="embed-responsive-item" name="load_payment" width="750" height="900" frameborder="0" scrolling="no">
</iframe>
<form:form id="send_hptoken" action="https://test.authorize.net/payment/payment" method="post" target="load_payment">
<input type="hidden" name="token" value="${token}" />
</form:form>
</div>
</div>
</div>
This is the iframecommunicator:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IFrame Communicator</title>
<script type="text/javascript">
function callParentFunction(str) {
if (str && str.length > 0 && window.parent.parent
&& window.parent.parent.CommunicationHandler && window.parent.parent.CommunicationHandler.onReceiveCommunication) {
var referrer = document.referrer;
window.parent.parent.CommunicationHandler.onReceiveCommunication({qstr : str , parent : referrer});
}
}
function receiveMessage(event) {
if (event && event.data) {
callParentFunction(event.data);
}
}
if (window.addEventListener) {
window.addEventListener("message", receiveMessage, false);
} else if (window.attachEvent) {
window.attachEvent("onmessage", receiveMessage);
}
if (window.location.hash && window.location.hash.length > 1) {
callParentFunction(window.location.hash.substring(1));
}
</script>
</head>
<body></body>
</html>
It seems nothing is logged into the console. If there is a response coming it should enter the switch case 'transactResponse' in the hostedOrderPage and log it to the console.
I had a similar problem. Make sure Test Mode is off on the Sandbox account first. Also I believe I had to add Content-Security-Policy for all the related domains plus frame-ancestors 'self' to the Header of the form. I build a string for the local domain and the remote domain, in my case it was test.authorize.net, and add that as a attribute. I build the forms dynamically.
See this link at the Dev forms for more information about the CSC issue.

Can a user control be rendered on the click event of a button?

I have created a user control which actually creates an empty dialog box for application form. I wanted to render this user control on the click event of a button(like we render partial views). I have an .aspx page that contains a button. On clicking the button the user control that creates a dialog, opens up. Below is the jquery code written to open the dialog in a user control:
Jquery
createAliasPopUpForm: function (rowNumberId) {
// debugger;
var self = this;
var dat = $("input[id*='hdnAliasRecordmetaData']").val();
self.metaDataColumns = JSON.parse(dat);
//debugger;
// now bind update data to pop up
if (self.metaDataColumns.length > 0) {
if (rowNumberId != 'undefined' && rowNumberId != null) {
self.rowNumber = rowNumberId;
// fill alias record to meta data
var listdata = $("input[id*='hdnAliasRecordList']").val();
var aliasList = JSON.parse(listdata);
if (aliasList.Rows.length > 0) {
$.each(aliasList.Rows, function (i, val) {
if (this.RowNumber == rowNumberId) {
self.fillAliasRecord(self.metaDataColumns, this.Columns);
return false;
}
});
}
}
else {
// right now cloumn list has MDM record value so need to clear that value only
$.each(self.metaDataColumns, function (i, val) {
this.Value = '';
});
}
// sort array
//self.metaDataColumns.sort(common.dynamicSortMultiple("GroupOrder", "MetadataId"));
self.metaDataColumns.sort(common.dynamicSortMultiple("GroupOrder", "ColumnNumber"));
self.createPopupHtml(self.metaDataColumns, rowNumberId);
self.init();
$('#popUpHeader').find('h4').remove();
$('#popUpHeader').append(' <h4 class="modal-title" >Alias Record</h4>');
$("#updateConfirmPopUp").dialog({
autoOpen: true,
width: 600,
resizable: false,
draggable: false,
modal: true,
show: { effect: 'blind' }
});
}
},
userControl
<%# Control Language="C#" AutoEventWireup="true" CodeFile="AddAlias.ascx.cs" Inherits="OCM.Phoenix.WebToolsFramework.Server.Modules.MDMAdmin.AddAlias" %>
<script language="javascript" type="text/javascript" src='<%= ResolveClientUrl("~/scripts/jquery-1.4.2.min.js") %>'></script>
<script language="javascript" src="../Scripts/jquery.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/jquery-ui.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/bootstrap.min.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/Common.js" type="text/javascript"></script>
<script language="javascript" src="../Scripts/AdminEdit.js" type="text/javascript"></script>
<asp:HiddenField ID="hdnAliasRecordmetaData" runat="server" />
<asp:HiddenField ID="hdnAliasRecordList" runat="server" />
<script>
$(function () {
adminEditForm.createAliasPopUpForm();
});
</script>
code behind file just contains the load event
aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="AddAliasPage.aspx.cs" Inherits="Modules_MDMDataHub_AddAliasPage" %>
<%# Register Src="UserControls/AddAlias.ascx" TagPrefix="uc" TagName="alias" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script src="Scripts/jquery.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<script src="Scripts/AdminEdit.js"></script>
<body>
<form id="form1" runat="server">
<div>
<uc:alias ID="alias" runat="server" />
<br />
<asp:button ID="btn1" OnClick="btn1_Click" runat="server"> </asp:button>
</div>
</form>
</body>
</html>
Although, I have created the click event of the button, that calls the below function to render the html of the user control. but its actuaaly not working as it keeps giving me an errer as the hdnmetadatavalue must be inside the form tag. I did it but still i get the error. Am i doing something wrong here? Please help
private string RenderControl()
{
var sb = new System.Text.StringBuilder();
using (var stWriter = new System.IO.StringWriter(sb))
using (var htmlWriter = new HtmlTextWriter(stWriter))
{
var p = new Page();
var ctrl = (AddAlias)p.LoadControl("~/Modules/MDMDataHub/UserControls/AddAlias.ascx");
ctrl.Visible = true;
// do your own init logic if needed
p.Controls.Add(ctrl);
ctrl.RenderControl(htmlWriter);
return sb.ToString();
}
}
By reviewing your code:
var ctrl = (AddAlias)p.LoadControl("~/Modules/MDMDataHub/UserControls/AddAlias.ascx");
// ... other lines
ctrl.RenderControl(htmlWriter);
I assume you are trying to call RenderControl method for user control to HTML rendering, where the page will raise form tag exception if the user control was rendered outside defined form tag with runat="server".
Use Page.VerifyRenderingInServerForm method on page code behind to ensure all user controls render properly:
public override void VerifyRenderingInServerForm(Control control) {
// nothing to override here
}
public override boolean EnableEventValidation {
get { return false; }
}
Reference: UserControl's RenderControl is asking for a form tag in (C# .NET)

passing server side variable to linked javascript file

I am building a multilingual web application in which i have a .aspx.cs file
public partial class example:System.Web.UI.Page
{
private string message="message to be displayed depending on user language";
public string Message
{
get{return message;}
set{}
}
}
and a .aspx file in which i have linked a javascript file for validating user input
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript" src="Scripts/DataValidation.js"></script>
</head>
<body>
<form id="form1" runat="server" onsubmit="return validation()">
<asp:TextBox ID="tbSupplierName" CssClass="marginspace" runat="server" Width="150px" MaxLength="30"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click" />
</form>
</body>
</html>
my DataValidation.js file loks like this
function validation()
{
var SupplierName = document.getElementById('tbSupplierName');
if (SupplierName.value.length == 0)
{
alert('please enter supplier name');//here i want to display server side variable 'message'
return false;
}
}
The problem is i want to pass my server side variable 'message' to the linked external javascript file DataValidation.js and display it in alert
I have tried below code but it is not working
function validation()
{
var message='<%=Message%>';
var SupplierName = document.getElementById('tbSupplierName');
if (SupplierName.value.length == 0)
{
alert(message);
return false;
}
}
Help me to solve the problem.Thanks in advance.
You can declare global JavaScript variable in your ASP.NET page
<script>
message='<%=Message%>';
</script>
Then you can use it directly in JS file
function validation() {
var SupplierName = document.getElementById('tbSupplierName');
if (SupplierName.value.length == 0) {
alert(message);
return false;
}
}

Categories