Modify form action with javascript - c#

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);
}

Related

How can I change culture when the use click on a button?

I've created two resources files inside a folder. And I'm using each on of them as language resource for my website.
inside the Global.asax I've used the following code to change the language:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
string culture = "en";
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
}
The issue is that, every time I want to change the language I have to access the code above and change the culture value.
Is there anyway to accomplish that with Button click event ?
For using buttons to switch languages, you could try to refer to the following methods and codes.
The project structure is as follows:
Page1.aspx.resx:
Page1.aspx.ku.resx:
Page2.aspx.resx:
Page2.aspx.ku.resx:
The code of Page1.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="Language.Page1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="English" Width="80px"></asp:Label>
<asp:Button ID="Button2" runat="server" Text="en-us" OnClick="Button2_Click" />
</div>
<p>
<asp:Label ID="Label2" runat="server" Text="Kurdish" Width="80px"></asp:Label>
<asp:Button ID="Button3" runat="server" Text="ku" OnClick="Button3_Click" />
</p>
<p>
<asp:Button ID="Button1" meta:resourceKey="Button1" runat="server" Text=" Hello" />
</p>
</form>
</body>
</html>
The code of Page1.aspx.cs:
using System;
using System.Globalization;
using System.Threading;
namespace Language
{
public partial class Page1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void InitializeCulture()
{
if (Session["lang"] != null)
{
Culture = Session["lang"].ToString();
UICulture = Session["lang"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Session["lang"].ToString());
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Session["lang"].ToString());
base.InitializeCulture();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["lang"] = Button2.Text;
Response.Redirect("Page1.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["lang"] = Button3.Text;
Response.Redirect("Page1.aspx");
}
}
}
The code of Page2.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Page2.aspx.cs" Inherits="Language.Page2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" meta:resourcekey="Label1" Text="ok"></asp:Label>
</div>
</form>
</body>
</html>
The code of Page2.aspx.cs:
using System;
using System.Globalization;
using System.Threading;
namespace Language
{
public partial class Page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void InitializeCulture()
{
if (Session["lang"] != null)
{
Culture = Session["lang"].ToString();
UICulture = Session["lang"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Session["lang"].ToString());
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Session["lang"].ToString());
base.InitializeCulture();
}
}
}
}

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);
}
}

Loading a dynamically created radio button list

I am trying to generate a dynamic radio button list, but the issue is that the dynamic list does not show on page load. Only the Submit button shows. Here is the code I am using:
<asp:PlaceHolder runat="server" ID="PlaceHolder1"/>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" />
<asp:Label runat="server" ID="Label1"/>
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
protected void Button1_Click(object sender, EventArgs e)
{
var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList;
Label1.Text = radioButtonList.SelectedValue;
}
private void LoadControls()
{
var tmpRBL = new RadioButtonList();
tmpRBL.ID = "1";
for (int i = 1; i <= 5; i++)
{
var tmpItem = new ListItem(i.ToString(), i.ToString());
tmpRBL.Items.Add(tmpItem);
}
PlaceHolder1.Controls.Add(tmpRBL);
}
WebForm1.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"/>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" />
<asp:Label runat="server" ID="Label1"/>
</div>
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
protected void Button1_Click(object sender, EventArgs e)
{
var radioButtonList = PlaceHolder1.FindControl("1") as RadioButtonList;
Label1.Text = radioButtonList.SelectedValue;
}
private void LoadControls()
{
var tmpRBL = new RadioButtonList();
tmpRBL.ID = "1";
for (int i = 1; i <= 5; i++)
{
var tmpItem = new ListItem(i.ToString(), i.ToString());
tmpRBL.Items.Add(tmpItem);
}
PlaceHolder1.Controls.Add(tmpRBL);
}
}
}
It works correct. I hope it will be helpful.
You could define an empty RadioButtonList control which you then populate with items on Page_Load. Would have the advantage that you don't have to create it manually. Also using the DataBind mechanism the control offers you together with an ObjectDataSource is a better solution (the Select method of the ObjectDataSource should return the items).
But aside this, maybe AutoEventWireup of the #Page directive (first line in the markup of the ASPX page) is set to false. If so the Page_Load event handler is not called. The directive usually looks like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
I copied the rest of your code and everything runs just fine.

The footer CSS does not work when the page loads dynamic content at button click

.html
<%# 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>
<link href="dark.css" rel="stylesheet" type="text/css" id="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="CaptionLabel" runat="server"></asp:Label>
<asp:TextBox ID="NumberTextbox" runat="server">(empty)</asp:TextBox>
<asp:Button ID="SquareButton" runat="server" Text="Square" style="background-color:Blue; color:White;" />
<asp:Label ID="ResultLabel" runat="server" Text="(empty)" CssClass="reverse"></asp:Label>
<p>
<asp:Label ID="Label1" runat="server" CssClass="footer1"
Text="Label Label Label Label LabelLabelLabel Label Label Label Label Label Label Label"></asp:Label>
</p>
<asp:RadioButton ID="radioDark" runat="server" AutoPostBack="True"
Checked="True" GroupName="grpSelectStylesheet"
oncheckedchanged="SwitchStylesheets" Text="Dark" />
<br />
<asp:RadioButton ID="radioLight" runat="server" AutoPostBack="True"
GroupName="grpSelectStylesheet" oncheckedchanged="SwitchStylesheets"
Text="Light" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SwitchStylesheets(object sender, EventArgs e)
{
if (radioDark.Checked)
stylesheet.Href = "dark.css";
if (radioLight.Checked)
stylesheet.Href = "light.css";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=DateTime.Now.Second;
for (int i = 0; i < count; i++)
{//for
Label q = new Label();
q.ID = DateTime.Now.Second.ToString();
q.Text = DateTime.Now.Second.ToString();
string spacee = "<br />";
Label space = new Label();
space.Text = spacee;
form1.Controls.Add(q);
form1.Controls.Add(space);
}//for
}
}
When the button is clicked, it works as it should but the footer does not register the expansion of the page.
Your code is completely wrong. you cannot change the stylesheet like this for a control even if the autopostback is set to true.
UPDATE: Here's how you should do it:
1- Remove the .css reference from your page.
2- Add this method to your page:
private void UpdateStylesheet(string filepath)
{
HtmlLink newStyleSheet = new HtmlLink();
newStyleSheet.Href = filepath;
newStyleSheet.Attributes.Add("type", "text/css");
newStyleSheet.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(newStyleSheet);
}
3- Add this line to your page_load event:
UpdateStylesheet("dark.css");
4- Handle the SwitchStylesheets like this:
if (radioDark.Checked)
UpdateStylesheet("dark.css");
if (radioLight.Checked)
UpdateStylesheet("light.css");

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