On the Button's Click event, ow can you disable the button, and also call its event handler?
I have tried this:
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Enabled = false;
}
This doesn't work in IE, Mozilla, or Chrome.
You could try adding this :
protected void Button1_Click(object sender, EventArgs e)
{
// Do some stuff here
Button1.Attributes.Add("onclick", "javascript:return false;");
Button1.Enabled = false;
}
<asp:Button ... OnClientClick="disableButton(this);" />
<script type="text/javascript">
function disableButton(button)
{
//need to delay a few ms so that the button posts back before being disabled
var buttonToDisable = button;
setTimeout("reallyDisableButton()"), 2);
}
function reallyDisableButton()
{
buttonToDisable.disabled = true;
}
</script>
I assume that your problem is that people are clicking a button several times (because the page it taking a while to load), thus kicking off the event several times and you only want them to be able to do it once. This will disable the button after it posts back preventing accidentally sending multiple concurrent postbacks.
Related
In my Sharepoint 2010 app, I'm handling most events client-side with jQuery. However, for the saving of data to the Sharepoint list, and the generation of a PDF file with that data, I want to handle that server-side, with C#.
I tried to invoke a C# event this way:
0) Aded an HTML button in my project's *.ascx file:
<button type="button" name="saveData" id="saveData">Save Data</button>
1) Added jQuery to respond to that button being clicked (in the same *.ascx file):
$("#saveData").click(function () {
$('#hiddenSave').trigger('valuechanged');
});
2) Created a hidden element in the server-side C# (in the *.ascx.cs file):
HiddenField hiddenSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
hiddenSave = new HiddenField();
hiddenSave.ID = "hiddenSave";
hiddenSave.ValueChanged += new EventHandler(hiddenSave_ValueChanged);
this.Controls.Add(hiddenSave);
}
protected void hiddenSave_ValueChanged(object sender, EventArgs e)
{
GeneratePDF();
}
private void GeneratePDF()
{
;//bla
}
But I never reach the "ValueChanged" event handler; $("#saveData").click() fires, but not hiddenSave_ValueChanged().
So do I need a tweak to this, or a completely different approach? How can I do as much as possible client-side with jQuery, but also run server-side/C# code where necessary, in a Sharepoint 2010 app?
UPDATE
A little more detail, and about additional things I've tried: I'm creating a button on a Sharepoint page dynamically (in C#) in my *.ascx.cs file:
Button btnSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Visible = false;
this.Controls.Add(btnSave);
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Text = "You clicked me!";
PostTravelData ptd = new PostTravelData();
}
I set it visible at the right time in the client-side jQuery in the *.ascx file:
$('#btnSave').show();
However, clicking the button does not reach the btnSave_Click() event - the breakpoint there is never reached, nor is the button's text changed. Why not?
Even when I don't set the button invisible (comment out the "btnSave.Visible = false;" line), the click handler isn't reached...is Page_Load() too late? Is there an earlier page event I can use that would work?
I tried moving it from Page_Load() to OnPreRender(), too, like this:
protected void OnPreRender(EventArgs e)
{
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
//btnSave.Visible = false;
this.Controls.Add(btnSave);
}
...(and OnRender()) but the button doesn't even display...
And, trying a different tack, I commented out the dynamic creation server-side code and tried to attach to a button created in the HTML (*.ascx file):
<button type="button" name="saveData" id="saveData" runat="server" onclick="saveData_Click">Save Data</button>
(by adding the "runat server" and the onclick handler), and then adding this "code-behind" (*.ascx.cs)):
protected void saveData_Click(object sender, EventArgs e)
{
PostTravelData ptd = new PostTravelData();
SaveToList(ptd);
GeneratePDF(ptd);
}
...but there was still no joy in Mudville -- the breakpoint in the handler is not reached.
Yet another attempt was:
In the *.ascx:
<asp:Button runat="server" id="saveData" name="saveData" onclick="saveData_Click" Text="Bla" />
In the code-behind:
saveData.Click += saveData_Click;
The "Bla" button is created, but clicking on it reaches not the breakpoint in the "saveData_Click" handler.
I even adapted some code from here like so:
Button btnSave = null;
. . .
protected override void CreateChildControls()
{
btnSave = new Button();
btnSave.Width = new Unit(150, UnitType.Pixel);
btnSave.Text = "Can you see me?";
btnSave.Click += new EventHandler(btnSave_Click);
Controls.Add(btnSave);
}
...but I still do not reach the "protected void btnSave_Click(object sender, EventArgs e)" handler when I click the button.
Surely there's a way to get a handle on the button server-side and manipulate it (specifically, respond to its click event)...?!?
First of all, as far as I know, there is no such event for input type hidden in a ascx page. If you create the input type hidden with runat server in the ascx code then you'll see that when you try to add this event it's not available. However there are other events like OnClick that you can simulate to get the desired result.
i have 2 server side asp.net buttons , i need to automate the buttons clicks.
i.e. After page_load, i need to click button1 and after its results are shown on the page, wait for 10 seconds and click button2 .
i tried the following sample code
protected void Page_Load(object sender, EventArgs e)
{
Button1_Click(Button1, null);
Thread.Sleep(10000);
Button2_Click(Button2, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button1";
}
protected void Button2_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button2";
}
}
i had 2 obeservations (maybe useful):
always Button2_Click(Button2, null); event is the latest when the page is fully loaded (which is obvious).
Page_Load(object sender, EventArgs e) doesnot
hit atall when programatically clicked the button.
Any idea how to achieve the solution.
What you are doing in your example is to call the handlers of button1 and button2's click events, that is not the same as having the user click the buttons, and for the form to postback to the server.
If you want the buttons to click them selves and having the post back to the server you need to add javascript that clicks the buttons for you.
If you want a javascript which hits a button for you after X seconds, i would do something like this:
in your aspx page:
<asp:button ID="Button1" runat="server" ClientIDMode="Static" OnClick="Button1_Click">
</asp:button>
in your javascript files or some block on your page:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("Button1").click();
}, 10*1000); // 10 seconds
</script>
Important to note here is that you have to either set ClientIDMode="Static" on your button, otherwise it might have a very obscure name if you are using master pages, or you can do:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%= Button1.ClientID %>").click();
}, 10*1000); // 10 seconds
</script>
if you have the javascript in your .aspx file rather then its own .js file.
ps: if you do Thread.Sleep(X) in an aspx page, you will only make the users browser wait for the X milliseconds more for the page to load, code run before the sleep will not be submitet to the clients browser in the way i think you want it to do.
Button_Click is server event, when invoked from client, browser post the relavent data to server and request of new page content, at that time Page_load is invoked.
if you want to do some thing, encapsulate action to some method and call that method in pre-render. Or other wise, use JavaScript.
protected void Page_PreRender(object sender, EventArgs e)
{
UpdateButton1()
Thread.Sleep(10000); // no need to put sleep
UpdateButton2();
}
protected void Button1_Click(object sender, EventArgs e)
{
UpdateButton1();
}
protected void UpdateButton1()
{
changeLabel.Text = "Button1";
}
I am uploading large file to Amazon S3 with Progress Bar, I am displaying Jquery progress bar, following This
Every thing is working fine, but there are two problems
If during processing user Select another file or Click Upload button multiple times, the progress bar count get increased
I have disabled FileUpload Control on button upload click event, but its not disabling the button upload control
This is How I am doing:
protected void btnupload_Click(object sender, EventArgs e)
{
if (FileVideoUpload.HasFile)
{
FileVideoUpload.Enabled = false;
btnupload.Enabled = false;
System.Threading.Thread.Sleep(8000);
//Upload File on Amazon S3
lblmsg.Text = "Video uploaded Successfully";
FileVideoUpload.Enabled = true;
btnupload.Enabled = true;
}
}
I also tried this,but still button is not disabling
protected void Page_Load(object sender, EventArgs e)
{
btnupload.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnupload, null) + ";");
}
Also I have tried disabling it in JS.
I want to disable both controls while processing.
Try this with Jquery :-
$('#FormId').one('submit', function() {
$(this).find('input[type="submit"]').attr('disabled','disabled');
// find input type submit button or any other buttons which u want //
});
try this if #btnupload is in fact the button that you want to be clicked and disabled. I didn't quiet get that.
$('#btnupload').on('click',function(){
$(this).prop('disabled',true);
});
and later for enabling it again use:
$('#btnupload').prop('disabled',false);
you can disable it on click event
$('#btnupload').on('click',function(){
$(this).prop('disabled','disabled');
});
What way is standard/ recommended to do the following:
When a user raises the Page_Command "Save" or "Send," I want to run a method. If the method returns false, I want to send the user back to the page and display a message.
All of the data they entered in the form should still be there. The message would have a button that reads, "Send Anyway/ Regardless." If they click it, it will send.
I know I could do this via a webservice and jQuery, but I am asking how I would do this via WebForms.
Here is my basic code:
protected void Page_Command(Object sender, CommandEventArgs e)
{
if ( e.CommandName == "Save" || e.CommandName == "Send" )
{
// run method
}
}
There are several ways you could do this.
One option might be to a button with the text "Save", and another with the text "Send anyway". Make the second button invisible to begin with, and the first visible.
When the first button is clicked, it should run the validation-logic. If validation succeeds, submit - otherwise, hide the first button, and set the other one to visible.
When / if the second button is clicked, the submit is performed without validation.
Update:
With some minor modifications, you should be able to do something like this:
Markup:
<asp:Button runat="server"
ID="myFirstButton"
OnClick="SubmitWithValidation" />
<asp:Button runat="server"
ID="mySecondButton"
Visible="False"
OnClick="SubmitData" />
Code:
protected void SubmitWithValidation(object sender, EventArgs e)
{
if (ValidateMyData())
{
SubmitData(sender, e);
}
else
{
mySecondButton.Visible = true;
myFirstButton.Visible = false;
}
}
private bool ValidateMyData()
{
// Validate stuff
return isValid;
}
private void SubmitData(object sender, EventArgs eventArgs)
{
// Logic to submit your data here
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If page loads for first time
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); // Assign the Session["update"] with unique value
//=============== Page load code =========================
//============== End of Page load code ===================
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString()) // If page not Refreshed
{
//=============== On click event code =========================
Label1.Text = TextBox1.Text;
//lblDisplayAddedName.Text = txtName.Text;
//=============== End of On click event code ==================
// After the event/ method, again update the session
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else // If Page Refreshed
{
// Do nothing
}
}
protected override void OnPreRender(EventArgs e)
{
ViewState["update"] = Session["update"];
}
}
This is not working for high resolution gradient background.
Consider wrapping your button and the label in an updatepanel control, which uses AJAX to refresh their contents.
The rest of the page will not be reloaded and the action will not affect the browser navigation.
See this page on how an updatepanel control works.
Since you are handling the button click event in server side there has to be a postback to handle it.
If you do not want a post back to happen change the event handling to "client click"
//Heinzi code worked for me just made a small change in OnPreRender event, assign the ViewsState value when its not post back
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
ViewState["update"] = Session["update"];
}
}