No response when call button click in javascript - c#

Good day,
I have a aspx contain a button with ID button1, the following is my aspx code :
<div>
<asp:LinkButton ID="lnkView" CommandName="VIEW" runat="server">View</asp:LinkButton>
<asp:Button ID="button1" runat="server" Text="OK" onclick="button1_Click" />
</div>
/*
some code here
*/
<script>
function test()
{
document.getElementById("<%=button1.ClientID %>").click();
alert("hello");
return true;
}
</script>
The following is my aspx code behind:
//some code here
lnkView.Attributes.Add("onclick", "return test()");
//some code here
protected void button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Javascript", "<script>alert('Record Added Successfully')</script>", false);
}
As you can see, my linkView link button have a javascript function test() when click on it.
I can alert the "Record Added Successfully" by click on the Button1.
However, when I click on linkView link button, the "Record Added Successfully" didnt alert, it only alert "Hello".
I think I am missunderstand in some programming concept.
Kindly advise.
Thanks.

This will trigger the event in code behind.
Try this in your .aspx page:
//Code:
<script type="text/javascript">
function test(parameter)
{
__doPostBack('button1_Click', parameter)
}
</script>

You can fix this by returning false instead of true as the result of the function test(). This way you will cancel default behavior of the link with ID lnkView ie sending form

Related

Avoid page refresh click on Button Asp.net c#

enter code here NET application, I have inserted a button that call a Javascript function (OnClick event) and a asp.net function (OnClick event)
The problem is that when I click the button, it refreshes the page.
How can I avoid the page refreshes click on asp button using javascript?
document.getElementById('pageurl').innerHTML = "tryfblike.aspx";
$('#<%= btnsave.ClientID %>').click();
$('#auth-loggedout').hide();
<asp:Button runat="server" ID="btnsave" OnClick="btnsave_Click();" Visible="true" style="display: none;" />
protected void btnsave_Click(object sender, EventArgs e)
{
objda.agentid = "2";
string currenttime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
objda.datetime = currenttime;
ds = objda.tbl_log();
}
First to call JavaScript function, use OnClientClick.
To avoid page refresh, after your function call add return false;
For example:
<asp:Button ID="btnSubmit" runat="Server" OnClientClick="btnsave_Click(); return false;" />
in java script you can use return false.
if you want prevent whole page referesh use ajax.
FirstYou can call javascrip onclick and then simply add
return false;

JS function calling from the code behind Issue

I have a JS function (Show alert box), and have a link button in ASP page, On click event from code behind for this link button I want to call this function and then redirect to certain page.
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
Response.Redirect("myPage.aspx");
}
Here when I click on the link button, it simply don't display the alert box/window and redirect to the page.
You should use LinkButton.ClientClick instead of LinkButton.Click event.
Click event is handled on server. When user clicks the button, page is posted back to server and code is executed on server side.
ClientClick event is really a name of JavaScript function which should be executed.
You should probably do something like this:
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClientClick="showMyAlertAndSubmit()"></asp:LinkButton>
<script type="text/javascript">
function showMyAlertAndSubmit(){
alert("Your password is being changed");
// submit your form
}
</script>
Why your current code doesn't work
You currently send script for showing a message, and redirect at the same time. This means that browser receives instructions to show a message and to redirect, and it redirects the user before showing the message. One approach could be to redirect from client side. For example:
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
and on client side
function myFunction() {
// show your message here
// do other things you need
// and then redirect here. Don't redirect from server side with Response.Redirect
window.location = "http://myserver/myPage.aspx";
}
Other options
Since you need to first perform checks on server side before saving data and redirecting, you can use ajax to call server without performing postback.
Remove Click handler, and only use ClientClick:
function myFunction() {
$.ajax({
type: "POST",
url: "myPage.aspx/MyCheckMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
ShowAlert();
window.location = "http://myserver/mypage.aspx";
}
});
}
For more details please check this tutorial.
Change your code like this:
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" OnClientClick="myFunction()" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
Response.Redirect("myPage.aspx");
}
Change your javascript function to :
<script type="text/javascript" language="javascript">
function myFunction() {
// alert will stop js execution
alert("document is ready!");
// then reload your page
__doPostBack('pagename','parameter');
}
</script>
And call it from code-behind with this function :
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
//do your job here
//then call your js function
ScriptManager.RegisterStartupScript(this,this.GetType(), "CallMyFunction", "myFunction();", true);
}
What you're missing is waiting for JavaScript alert dialog to popup and then redirect to the page.
In order to do this you need to tell button to wait for JavaScript alert dialog to popup and then do the Server side work after.
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function alertBeforeSubmit() {
return alert('Document Ready');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="Do" runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="return alertBeforeSubmit();" />
</div>
</form>
</body>
CS:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}

How to call a javascript function before and after button click event call in asp.net

i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example:
Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager> in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
You can call Java scrip function before server side click using OnClientClick():
aspx(design)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Test() {
alert('client click');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="btn" runat="server" ID="btn"
OnClick="btn_Click" OnClientClick="Test()" />
</div>
</form>
</body>
</html>
.cs
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Server Click");
}
First time you can call your javascript function in Button's OnClientClick event passing your function name.
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click" OnClientClick="return functionNAME();"/>
Second time, in your button click event btnLogin_Click call js as follow
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>functionNA();</script>", false);
For calling it before, you could consider using onload function, like this example:
<body onload="myFunction()">
For calling it afterwards, just link the button to execute JS onClick?
I don't think I quite understand your intentions.

Check which ASP.NET was clicked

I have the following div (normally hidden)
<div id="confirmDialog" class="window" style="background-color:#f2f4f7; border:1px solid #d9a0e2; text-align:center; height:100px; position:fixed; padding:10px; top:50% " runat="server" visible="false">
<br /> You already have a leave request on the chosen date. Are you sure you want to submit this request?<br /><br />
<asp:Button ID="BtnConfirm" runat="server" Text="Yes" Width="60px" />
<asp:Button ID="BtnNo" runat="server" Text="Cancel" onclick="BtnNo_Click" />
</div>
When a user clicks submit, code starts to execute and if the below function is true I would like to show a confirmation dialog before continuing to execute code:
protected void BtnAdd_Click(object sender, EventArgs e)
{
//some validations
if (new LeaveLogic().GetEmployeeLeaveRequestByDate(username, Convert.ToDateTime(TxtBoxDate.Text)) > 0)
{
confirmDialog.Visible = true;
/if BtnConfirm is click continue to execute code
//else stop
How can I do this via asp.net/jQuery?
You must split the code in 2 different parts: one that executes and after is done pops up a confirmation dialog, and a second part where you submit the form to execute the remaining piece. You can't do this in one shot because you can't have server-side code execute, pop up a confirm dialog on the client side and then continue on the server side.
What you have to do is (in pseudo code)
button1_Click()
{
Execute_logic;
use scriptmanager to trigger a JavaScript function that displays the confirmation dialog;
}
The JavaScript function should:
function askConfirm()
{
if(confirm('want to continue?'))
submit_the_form to execute second part of the process();
else
return false;
}
Server-side code again:
//This is the method that should execute after the JavaScript function submits the form
Handler_ForSecondPartOfTheRequest()
{
execute second part of the logic;
}
You can do in couple of ways.
By intercepting the click event by Jquery
Other adding script in your code.
protected void Button1_Click(object sender, EventArgs e)
{
ClientScriptManager CSM = Page.ClientScript;
if (!ReturnValue())
{
string strconfirm = "<script>if(!window.confirm('Are you sure?')){window.location.href='Default.aspx'}</script>";
CSM.RegisterClientScriptBlock(this.GetType(), "Confirm", strconfirm, false);
}
}
bool ReturnValue()
{
return false;
}

Prevent Postback after opening jQuery dialog box

Page:
<body>
<form id="frmLogin" runat="server">
<asp:Button ID="btnClick" OnClientClick="openConfirmDialog();" OnClick="PopulateLabel" runat="server"/>
<div id="divDialog"></div>
<asp:Label ID="lblText" runat="server"></asp:Label>
</form>
</body>
JS
<script type="text/javascript">
$(document).ready(function() {
$("#divDialog").dialog({autoOpen: false,
buttons: { "Ok": function()
{
$(this).dialog("close");
},
"Cancel": function()
{
$(this).dialog("close");
}
}
});
});
function openConfirmDialog()
{
$("#divDialog").dialog("open");
}
C#
protected void Page_Load(object sender, EventArgs e)
{
lblText.Text = "";
}
protected void PopulateLabel(object sender, EventArgs e)
{
lblText.Text = "Hello";
}
This code opens me a dialog box with Ok and Cancel button but it do not wait for user activity and post the page immediately and the label gets populated. I need to call the c# function based on user activity. If user clicks "Ok" label should get populated and if user clicks "Cancel" it should not call the c# function. How do I achieve this?
First, to prevent the page from immediately posting back to the server, you need to cancel the default behavior of the click event by returning false from your handler:
<asp:Button ID="btnClick" runat="server" OnClick="PopulateLabel"
OnClientClick="openConfirmDialog(); return false;" />
Next, you need to perform the postback yourself when your Ok button is clicked:
$("#divDialog").dialog({
autoOpen: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
__doPostBack("btnClick", "");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
Note that the first argument to __doPostBack() is the name of the control (its UniqueID in ASP.NET terminology). Since the button is a direct child of the <form> element, we can hardcode its id in the __doPostBack() call, but things will get more complicated if it resides in a container hierarchy. In that case, you can use ClientScript.GetPostBackEventReference() to generate the appropriate call to __doPostBack().
EDIT: Since your page does not contain any postback-enabled control, __doPostBack() won't be defined on the client side. To work around that problem, you can use a LinkButton control instead of a Button control.
Added another button and used the jQuery click() event to trigger new button's click event which will in turn trigger the respective event handler in C#

Categories

Resources