I am using ASP.NET 3.5.
When the user click on say btnSubmit I want to first execute some JavaScript code and then execute some C#/VB.NET code.
Is this possible? If so how would one do it?
Thanks in advance!
This is very simple:
http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx
<%# Page Language="C#" %>
<script runat="server">
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Server click handler called.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" Runat="server"
OnClick="Button1_Click"
OnClientClick="return confirm('Ready to submit.');"
Text="Test Client Click" />
<br />
<asp:Label ID="Label1" Runat="server" text="" />
</form>
</body>
</html>
Have the JavaScript execute and then call a web service with xmlhttprequest from the javascript
There is onClientClick property - check this out http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Of course, you simply add an onClick event all JS code is executed before the postback.
If the code is for validation and you decide you don't want to submit you can return false and it won't post.
<asp:Button OnClientClick="" />
Thanks for the answer guys!
To execute a function from code behind one would do this in VB.NET
Protected Sub btnSubmit_Click(blah blah) Handles btnSubmit.Click
ClientScript.RegisterStartupScript(Me.GetType(), "hiya", "Message()", True)
lblLabel.Text = "Hello my name is Etienne!"
End Sub
Related
I have a simple web form with a single button:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWeb.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://unpkg.com/showmodaldialog"></script>
<script>
function showPopup() {
var ret = window.showModalDialog("Popup.aspx");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
How do I make that button open Popup.aspx with ShowModalDialog Polyfill from https://github.com/niutech/showModalDialog?
I tried Default.aspx.cs like this:
using System;
namespace DemoWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("OnClick", "showPopup()");
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
}
It works in IE with old showModalDialog, but in Chrome popup appears and immediately disappears.
Well, if you button click is to run server side code, then you get a full page post back, and that will re-load the page.
But, you CAN have that asp.net button call 100% browser side code and NOT run the button click event stub on the server.
You can use this format:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" OnClientClick="showpopup()";return false;" />
</div>
<script>
function showpopup() {
var ret = window.showModalDialog("Popup.aspx");
}
</script>
</form>
So, when you click on the asp.net button, it will call the client side function. (you use OnClientClick(). Also, we added a return false to that click event, and this will prevent the server side Button1_Click event from running. However, you can have the js code return true or false, and if the routine returns true, then the button_click (server side) code will run, but if your js returns false, then the server side event code will not run.
Also, showModalDialog has been REMOVED from most browsers. So it will not work. I suggest you adopt jQuery and also adopt jQuery.ui, and use that to pop up a dialog.
Also if a browser STILL DOES support showModalDialgo (and it HAS been removed), even if it worked, then 99% of popup blocks which now even browsers have turned on by default will block anyway.
So, to run the above with jQuery and also jQuery.ui, then your code to pop up the dialog will become this:
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" Width="94px" OnClientClick="showpage();return false;" />
<br />
<br />
<div id="poppagearea">
</div>
<br />
<script>
function showpage() {
var mydiv = $('#poppagearea');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool other page', width: '30%',
position: { my: 'top', at: 'top+150' },
buttons: {
'ok': function () {
mydiv.dialog('close');
// code here for ok click alert('user click ok');
},
'cancel': function () {
mydiv.dialog('close');
// code here for a cancel click alert('user click cancel');
}
}
});
}
</script>
</form>
So you CAN use a alert(); in pure js, or you can prompt the user with a confirm('do you want to do this'). But if you want to pop up a dialog - especially another page, then I would quite much suggest that jQuery and jQuery.UI are the way to go here.
Polyfill won't work with a server side control. Replace your asp button with an input type="button" and add the click event using addEventhandler with async and await. Control flow should stop on ShowModelDialog call then and will resume when you close the popup.
What would cause an asp Button not to fire after a partial update has occured?
<asp:UpdatePanel ID="upPan" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnSave" ClientIDMode="Static" runat="Server" Text="Save" CausesValidation="false" />
</ContentTemplate>
</asp:UpdatePanel>
The first time any button is fired inside the update panel the below routines fire in this order.
After a postback has occured triggering the button again causes a postback, both Load and PreRenderComplete events fire but the click event is skipped.
VB
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.PageLoad
//Runs everytime
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
//Doesn't fire after first postback.
End Sub
Protected Sub Page_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete
//Runs everytime
End Sub
FAILED RESOLUTIONS
Suggestions to resolve this include:
ChildrenAsTriggers= "True"
This is already the default behaviour of UpdatePanel and offers no change.
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
Again by default child controls of the panel cause an asynchronous postback and declaring triggers is redundant.
SUCCESSFUL RESOLUTION
If I simply change the asp:Button into an asp:LinkButton the issue is resolved.
SUMMARY
The postback is occuring but the click event is being missed when the sender is an asp:Button control.
Can anyone explain what would cause this behaviour?
First up, apologies my answer is in C#. It's also not much of an answer as I can't replicate your issue. The distinction between Buttons and LinkButtons is that a Button uses submit behaviour and a LinkButton uses a javascript postback. You could try putting UseSubmitBehavior="false" on your Button, that'll make it work like a LinkButton.
Here's my complete test code. Being C# I had to make a few changes as it doesn't have Handles - which maybe a key to the issue as C# and VB handle events slightly differently
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test3.aspx.cs" Inherits="Test3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="PageScriptManager" runat="server" />
<asp:UpdatePanel ID="upPan" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnSave" ClientIDMode="Static" runat="Server" Text="Button" CausesValidation="false" OnClick="btnSave_Click" />
<asp:LinkButton ID="lnkButton" ClientIDMode="Static" runat="Server" Text="Link Button" CausesValidation="false" OnClick="btnSave_Click" />
<asp:TextBox ID="txtBox" runat="server" TextMode="MultiLine" Rows="3" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
CodeBehind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtBox.Text = "Page_Loaded";
}
protected void btnSave_Click(object sender, EventArgs e)
{
txtBox.Text += "\n" + DateTime.Now.ToString("mm:ss:fff");
}
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
txtBox.Text += "\nPreRenderComplete";
}
}
Clicking the Button (or the LinkButton) works and updates the TextBox everytime:
Page_Loaded
55:54:185
PreRenderComplete
This question already has answers here:
How do I make a checkbox required on an ASP.NET form?
(6 answers)
Closed 9 years ago.
I've looked at a dozen previous answers on here nothing has worked for me. I need a form where a checkbox must be checked in order to submit. I am using C# and am pretty new to it, I just found out the RequiredFieldValidator that works with text box's won't work with checkboxes so I need another way to do this.
On submit the data in the fields gets sent to a MS SQL database. I have more fields then the one's shown below but I thought I would condense it for this post and removed everything but one text box and the checkbox I need validated upon submit.
I'd like it to do this on submit:
<form id="form1" runat="server">
<asp:Label ID="NameLbl" runat="server" Text="Label"></asp:Label><asp:RequiredFieldValidator
ID="NameRFV" runat="server" ErrorMessage="NameTxtBox"></asp:RequiredFieldValidator>
<asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>
<br />
<asp:Label ID="AliveLbl" runat="server" Text="Are you alive?"></asp:Label>
<asp:CheckBox ID="AliveChkBox" runat="server" />
<asp:Button ID="Submit" class="btn btn-primary" runat="server" Text="Submit" OnClick="Submit_Click" />
</form>
I've read about using CustomValidator but I can't get anything to function properly with it. People keep saying you need to compile/build your code for it to work and I simply don't no how to do that.
Will consider javascript options as well. I can also use a CheckboxList instead if you know of a better way to validate those.
In Submit_Click function, you could add a check for whether AliveChkBox.Checked is true. If it's false, you could show a MessageBox or something like that to inform user that it needs to be checked, then simply return from Submit_Click so that nothing will happen until it's checked.
You want to use
if (checkbox1.Checked)
btn1.enabled
else (checkbox1.disabled)
btn1.disabled
this.errorProvider1.SetError(checkbox1, "Must be checked to continue");
Here is the solution:
Code behind:
using System;
public partial class TestCheckBox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AliveScript", "<script>function CheckAlive(){ return document.getElementById('" + this.AliveChkBox.ClientID + "').checked; } </script>");
this.Submit.OnClientClick = "return CheckAlive();";
}
protected void Submit_Click(object sender, EventArgs e)
{
}
}
aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="TestCheckBox.aspx.cs" Inherits="TestCheckBox" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="NameLbl" runat="server" Text="Label"></asp:Label>
<asp:RequiredFieldValidator ID="NameRFV" runat="server" ErrorMessage="NameTxtBox" ControlToValidate="NameTxtBox"></asp:RequiredFieldValidator>
<asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>
<br />
<asp:Label ID="AliveLbl" runat="server" Text="Are you alive?"></asp:Label>
<asp:CheckBox ID="AliveChkBox" runat="server" />
<asp:Button ID="Submit" class="btn btn-primary" runat="server" Text="Submit" OnClick="Submit_Click" />
</form>
</body>
</html>
if (checkBox1.Checked == true)
button1.Enabled = true;
Use a code similar to this, just make it so button1 is not enabled on the properties
KeyPress or KeyDown events aren't available in System.Web.UI.WebControls.TextBox so one way to do it is using Java-Scripts, but want to fire some Sql queries at these events. is it possible to execute Sql queries from JavaScript? if not then how do I do it?
No, You cannot execute SQL from javascript. Your best bet is to use something like jquery and wire up an event to .change() (or something simiiar) and then make an ajax request to perform the sql query. A server side event (which doesn't exist) for textbox key press or key down would submit the page everytime and that just wouldn't work for the user. You might look into jquery ui autocomplete if you're looking to display some information
If you need to capture key events, you'll need to use Javascript.
You can use ajax to then send these keys to the server and perform actions.
My guess is that you're thinking of something along the lines of Google Suggest.
You can handle the key press event in the given way
But you can't fire SQL queries in these events.
<%# Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = "Start";
}
TextBox1.Attributes.Add("onkeyup", "rewriteLabel()");
}
</script>
<script type="text/javascript">
function rewriteLabel()
{
TextBox1.Text = Label1.text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head >
<title >test</title>
</head>
<body>
<form id="form1" runat="server">
<br />
<asp:TextBox ID="TextBox1" runat="server" /><br />
<asp:Label ID="Label1" Runat="server" BorderWidth="1px" />
</form>
</body>
</html>
On my ASPX page, there is a button with this code:
OnClick="save_Click"
Is it possible to execute Javascript before postback and if the result is true, then do the postback and go to method save_click?
There is a property called "OnClientClick" as well. Here you can specify a function that will validate (I'm guessing), or just run regular javascript.
If your data is not valid you can just return false; from the method. That should cancel your postback
you should use the very well known way: return confirm('bla bla bla')
adding this snippet to the onclick attribute of the button in the page or button prerender method, server side...
http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx
<%# Page Language="C#" %>
<script runat="server">
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Server click handler called.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" Runat="server"
OnClick="Button1_Click"
OnClientClick="return confirm('Ready to submit.');"
Text="Test Client Click" />
<br />
<asp:Label ID="Label1" Runat="server" text="" />
</form>
</body>
</html>
Possible duplicate of : Execute ClientSide before ServerSide in ASP.NET
I changed the definition of the __doPostback function to accomplish this:
<script type="text/javascript">
var originalDoPostback = __doPostBack;
__doPostBack = function (p1, p2) {
doSomethingCustomHere();
originalDoPostback(p1, p2);
};
</script>