Run a Javascript function before postback - c#

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>

Related

How to use ShowModalDialog Polyfill in ASP.NET Web Form?

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.

ASP.NET undefined from hiddenfield value

I'm trying to get the value from a hiddenfield but I'm getting an undefined alert. What am I doing wrong?
// Masterpage
...
<body>
<div class="container">
<asp:ContentPlaceHolder ID="MasterContent" runat="server"></asp:ContentPlaceHolder>
</div>
<script>
$(document).ready(function () {
alert($('#hiddenPersonId').val());
});
</script>
</body>
// Default.aspx
<asp:Content ID="Content" ContentPlaceHolderID="MasterContent" runat="Server">
<asp:HiddenField ID="hiddenPersonId" runat="server" Value="1" />
</asp:Content>
I tried other solutions but these are also not working:
alert($("#<%= hiddenPersonId.ClientID %>").val());
You could try setting ClientIDMode to static if you're .net 4+. You'll want to check that it is defined first. If you want/need the js to be on master page.
<script type="text/javascript">
$().ready(function () {
alert($('#hdnPersonId').val());
});
</script>
<asp:HiddenField ID="hdnPersonId" Value="1" runat="server" ClientIDMode="Static" />
It will not work from master page. You need to call it from Default.aspx or try
$('[id*="hiddenPersonId"]')
on master page but other pages that uses this master page should not have any control that contains hiddenPersonId in its id

JavaScript functions prevent C# functions from being executed?

On my aspx page I have two buttons. One calls some javascript and the other calls a C# function on the code-page. When I call the javascript file in the head of the document, the JavaScript function works well but the C# does not. Clicking on the button does not do anything. If I remove the javascript call then the C# function works normally.
How can I overcome this? It seems as if it is expecting to find the C# function within the JavaScript file.
ASP:
<head>
<script src="MyFunctions.js" language="javascript" type="text/javascript"></script>
</head>
<body>
<asp:Button id="btn1" Text="Submit" runat="server" OnClick="buttonSumbit_Click" />
<asp:Button id="btn2" Text="Show" runat="server" OnClientClick="buttonShow_Click()" />
</body>
C#:
protected void buttonSumbit_Click(object sender, EventArgs e)
{
//SOME CODE HERE
}
JavaScript:
function buttonShow_Click()
{
//SOME CODE HERE
}
You need to put all Asp.Net server controls inside a <form runat="server"></form> tag
You need to modify your javascript function call to be like this
<asp:Button id="btn2" Text="Show" runat="server" OnClientClick="return buttonShow_Click()" />
and make sure that your javascript function returns true so postback (execute C# function) happens. If your javascript function return false, postback to server won't happen.
I Suggest you to use this for calling javascript functions:
OnClientClick="if(!hidepopup())return false;"
you can also call javascript functions from codebehind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "jsfunction();", true);

how do I handle KeyPress or KeyDown events in asp.net?

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>

Execute ClientSide before ServerSide in ASP.NET

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

Categories