aspnet webforms disable button on submit - javascript

I have a small problem in Webforms. I'm trying to disable the submit button on submit, to prevent double posts.
The problem is, that the onclick method in codebehind is not getting called if the submit button is disabled during postback. Postback still occurs, but the buttons onclick method doesn't get called.
Is there a way to get around this?
Here a small demo of the problem:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApplication2._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script>
function disableButton() {
//$('#<%=btn.ClientID%>').attr('disabled', 'diabled');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal runat="server" ID="ltrDate" />
<asp:Button runat="server" ID="btn" OnClientClick="disableButton();" Text="Hit me!" OnClick="Unnamed_Click" />
</div>
</form>
</body>
</html>
codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_Click(object sender, EventArgs e)
{
Thread.Sleep(1000);
ltrDate.Text = DateTime.Now.ToString();
}
}
}
If this code is run, it works fine, but if the // is removed from the javascript method, the buttons onclick method is not being called anymore. (postback still occurs fine)
/Martin
Update:
It seems to be an old issue..
I never got this to work, because when the button is disabled client-side, its information is no longer posted back to the server, so its server-side click event does not fire. I suspect that's the behavior you're seeing.
If you do manage to make this work, I'd love to know how.
Ian Olsen
Wednesday, June 09, 2004

A more simple solution:
<asp:Button ID="btnFind" runat="server" Text="Find"
OnClientClick="if(this.alreadClicked == true) {this.disabled = true;
this.value = 'Wait...';} else {this.alreadClicked = true;}" EnableViewState=false
</asp:Button>
You disable the button anyway and also give the user a feedback "Wait...", but must use EnableViewState=false so the button reset to it's original state when the page refresh.

Ok.. I found the answer :)
The trick is to use Page.GetPostBackEventReference(btn). The method will insert a call to dopostback, and the right events will be fired.
The easy solution is to just insert that line after the javascript line that disables the button. Then it'll work, but if you have client side validation, that wont work. (Or, it'll work, but the submit button will be disabled if the user forgot to enter the required information).
Here's the demo from my original question edited to use client validation, and with the disabeling of the submit button on postback:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApplication2._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script>
$(function () {
if (typeof ValidatorUpdateDisplay != 'undefined') {
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplay(val);
//Bind();
if (val.isvalid) {
$('#<%=btn.ClientID%>').attr('disabled', 'disabled');
<%=Page.GetPostBackEventReference(btn)%>
}
}
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<div>
<asp:TextBox runat="server" ID="txtFirstname" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtFirstname" Display="Dynamic" EnableClientScript="true" ErrorMessage="Please enter your firstname" />
<br />
<asp:Literal runat="server" ID="ltrDate" />
<br />
<asp:Button runat="server" ID="btn" Text="Hit me!" OnClick="Unnamed_Click" />
</div>
</form>
</body>
</html>
Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_Click(object sender, EventArgs e)
{
Thread.Sleep(1000);
ltrDate.Text = DateTime.Now.ToString();
}
}
}

Related

asp.net webform will not let me run javascript

I've just followed this very basic code on Youtube and it works perfectly. However, I go to try the same code on my asp.net webforms website, have tried it in both chrome and edge, and javascript doesn't seem to want to run. Can anyone please tell me where I am going wrong? I am using Visual Studio 2015. I must have a setting turned off somewhere or something as it does not make any sense to me why a basic alert is failing to run.
Here is the basic code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="webform.aspx.cs" Inherits="webform" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function pleaseWork(){
alert("this is running");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button"/>
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "pleaseWork();", true);
}
}
If you just need this to execute on the client, then you probably don't need any server side controls for it. So the head section doesn't need to run on the server.
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="pleaseWork();"/>
OR
<input type="button" value="Button2" onclick ="pleaseWork();" />
Your button is missing an onclick attribute, so Button1_Click is not being called.
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Button_Click() doesnt fire with $().ready /function pageLoad()

This might be a silly question ..I m New to Client Side technology.. But i just wanted to know .. does Button_Click() wont Fire with $().ready function simply ?...
this is my Code
<%# Page Language="C#" CodeBehind="Default.aspx.cs" %>
<!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 id="Head1" runat="server">
<script type="text/javascript" src="http://code.jquery.com/Javascript/jquery-1.4.2.min.js"></script>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
}
</script>
<script type="text/javascript" language="javascript">
$().ready(){ alert(' '); }
----another try
$(document).ready()
---another try
function pageLoad() { alert(' '); }
--another try
$(document).ready(function() {
alert("Document is Ready Now!");
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
I tested it on FireBug ..$().ready wont fire before or After Button_Click() ..DO i Need to use Script Manager.. I have seen some suggestion ..
I Couldnt able to find something relevant ..PLease Suggest
jQuery document ready statement like this.
$(document).ready(function() {
alert("Document is Ready Now!");
});
use this ....kindly check have attach jquery library in your project or not.
Jquery
$(document).ready(function() {
$('#Button1').click(function(){
alert("Document is Ready Now!");
});
});
demo
Try $(document).ready()
This function will be executed before any other function in script.
why you use bellow code when use jquery use the second code
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
}
</script>
$(document).ready(function() {
$('#Button1').click(function(){
alert("this is alert!");
});
});
There is a problem with the jQuery CDN that you're using.
Hit this link http://code.jquery.com/Javascript/jquery-1.4.2.min.js. It will show up a 404 Not Found error.
Try other CDN's.
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
Hope it helps.
UPDATE
I think you've got the wrong path to the jquery.
It should be
http://code.jquery.com/jquery-1.4.2.min.js and not http://code.jquery.com/Javascript/jquery-1.4.2.min.js. Observe the difference.
The link point to Javascript directory which doesn't exist

PageMethods not defined despite copying example code

On another forum someone complained that PageMethods are not defined. And someone provided an answer that said ... 'look, this is how you get them to work'. So I copied their code and tried it. I am still seeing PageMethods not defined.
The page looks like this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PageMethods.aspx.cs" Inherits="PageMethods" %>
<!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>Untitled Page</title>
</head>
<body onload="GetFromServer();">
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true"></asp:ScriptManager>
<div>
</div>
</form>
<script type="text/javascript">
function GetFromServer()
{
PageMethods.GetHello(OnGetHelloComplete);
}
function OnGetHelloComplete(result, userContext, methodName)
{
alert("Result: " + result + "\n" +
"Context: " + userContext + "\n" +
"Method name: " + methodName);
}
</script>
</body>
</html>
And this is the code behind.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Web.Script.Services;
public partial class PageMethods : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetHello()
{
return "Hello From Server!";
}
}
When you run the page a javascript error occurs - 'PageMethods' is not defined.
This is a .net 2.0 web site.
I think this one will need .NET 3.5. I just used your exact code in a quick demo, and I was able to call the GetHello method without any trouble.

How to disable asp.net validator on client side?

I have very simple aspx page:
<%# 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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:textbox runat="server" ID="tbText" ValidationGroup="Address"></asp:textbox>
<br />
<asp:RequiredFieldValidator ID="rfvText" runat="server" ControlToValidate="tbText"
ValidationGroup="Address" ErrorMessage="RequiredFieldValidator">Enter text</asp:RequiredFieldValidator>
<br />
<asp:Button runat="server" Text="Submit" ID="btnSubmit" OnClick="Submit_Click"
ValidationGroup="Address" OnClientClick="DisableValidator();" />
<script type="text/javascript">
function DisableValidator() {
alert('Called and disable validators before submit');
var validator = document.getElementById("<%=rfvText.ClientID%>");
validator.validationGroup = "someGroup";
ValidatorEnable(validator, false);
}
</script>
</div>
</form>
</body>
</html>
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 Submit_Click(object sender, EventArgs e)
{
Validate("Address");
if (!IsValid)
{
throw new Exception("Page is no valid");
}
}
}
All elements on the page have ValidationGroup="Address", but I need disable my validator just before I click on the button. So, on client site it disables, but when I try to validate it on the server, my page isn't valid on the server but valid on client.
How can I disable validator on client to became disable on the server also?
Thanks!
You should use EnableClientScript="False" on the validation control, that is:
<asp:RequiredFieldValidator ID="rfvText"
runat="server" ControlToValidate="tbText"
ValidationGroup="Address"
EnableClientScript="False"
ErrorMessage="RequiredFieldValidator">Enter Text
</asp:RequiredFieldValidator>
You would have to programmably disable it when the page posts back, however you interpret that validator should be disabled on the client then would need to be replicated on the server, and set Enabled="false".
If you are using .NET 4, try using the EnableClientScript property. I've never used it myself but according to the docs, it should meet your needs.
Gets or sets a value indicating whether client-side validation is enabled.
<asp:Button runat="server" Text="Click Me" EnableClientScript="False" />

Refresh user control inside an update panel from javascript

I am working on a project where I want to refresh a part of the web page where i have a user control that contain dynamic data.user control will load data from a text file as this text file will update frequently. I need to refresh the user control alone not the whole page using javascript. I tried the following but it did not worked for me.
<%# Page Language="C#" %>
<%# Register src="ucTest.ascx" tagname="ucTest" tagprefix="uc1" %>
<script runat="server">
void button_Click(object sender, EventArgs e)
{
lbltest.Text = "Refreshed by server side event handler at " + DateTime.Now + ".<br>";
}
</script>
<!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>
<title>How to update an UpdatePanel with JavaScript</title>
<script type="text/javascript">
function UpdPanelUpdate()
{
__doPostBack("<%= button.ClientID %>","");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
Update the Panel
<asp:Button ID="button" runat="server" OnClick="button_Click" style="display:none;"/>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<ContentTemplate>
<uc1:ucTest ID="ucTest1" runat="server" />
<asp:Label ID="lbltest" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
my user control is.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ucTest.ascx.cs" Inherits="ucTest" %>
<table border="3">
<tr>
<td>
<% Response.WriteFile("TextFile.txt"); %>
</td>
</tr>
</table>
Here TextFile.txthas some information that will be changed frequently.
any help would be greatly appreciated.
To make things simpler, you can put the hidden button within the UpdatePanel so that you don't have to put async triggers. First keep the button visible and see if the update panel is refreshing or not. If yes then you can hide the button.
Next part is triggering the button by simulating click event. I will suggest you to use library such as jquery from cross-browser solution. For example,
function UpdPanelUpdate()
{
$("<%= button.ClientID %>").click();
}
For code __doPostBack("<%= button.ClientID %>",""); to work, you should try setting button's UseSubmitBehavior property as false.

Categories

Resources