Check which ASP.NET was clicked - c#

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;
}

Related

Issue with asynchronously removing displayed data

I am testing with the following code to display data and then remove it after a certain time, using async.
The problem I am having is that I want to display the label and text, then do the async however the async is running before the first part of my code.
Is there a way that I am able to run the code first and then do the async await?
<form id="form1" ondatabound="Page_Load()" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="false"></asp:Label><br /><br />
<asp:Button ID="Button1" class="btn btn-error" OnClick="Button1_Click" runat="server" Text="Button" /><br /><br />
<asp:TextBox ID="TextBox1" ReadOnly="false" Text="" Visible="true" runat="server"></asp:TextBox><br /><br />
<asp:TextBox ID="TextBox2" ReadOnly="false" Text="" Visible="true" runat="server"></asp:TextBox><br />
</div>
</form>
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//TextBox1.Text = "TestEmail";
//TextBox2.Text = "TestPassword";
}
//When Button1 is clicked then show/hide the title label
protected void Button1_Click (object sender, EventArgs e)
{
if (Label1.Visible == false)
{
Label1.Visible = true;
Label1.Text = "Please use this link to login: www.test.com";
TextBox1.Text = "TestingData";
}
else
Label1.Visible = false;
ClearMessages();
}
public async Task SyncTest()
{
await Task.Delay(5000); // 5 second delay
this.ClearMessages();
}
protected void ClearMessages()
{
TextBox1.Text = "";
TextBox2.Text = "";
Label1.Text = "";
}
}
As i mentioned in the comment. As soon as the page is rendered the backend has no connection to the page anymore thus it cannot empty the text. The better way to solve this would be to clean it on clientside by calling the script on clientside with
Page.ClientScript.RegisterStartupScript(GetType(), "cleanText", "cleanText());", true);
this will call the method below which will empty textbox1 after 5 seconds.
function cleanText(){
setTimeout(function() {
var txt1 = document.getElementById('<%= TextBox1.ClientID %>');
txt1.value = "";}, 5000);
}
regarding your concept and question:
...remove [data] after a certain time, using async [, or awaitable Task].
Is there a way that I am able to [render the page] and then do the async await?
to my knowledge, there is no framework support for async await and Task to cross Page Lifecycles, let alone compose mechanisms on a post rendered/unloaded page, so the answer is likely, no.
There is, however, asynchronous support for WebForm Applications with ASP.NET AJAX Extensions. You can achieve your desired behavior (code behind handling of control property changes in an asynchronous manner) with Partial Page Updates.

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;

No response when call button click in javascript

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

How to validate a form in ASP.NET using an image button, before raising the onClick event?

This may be a silly question but i'm a beginer here..
I created a form in asp.net and it's all fields are validated using validation controls on clicking an image button.It is working properly.After that i add an event to the button.This is the code of that button.
<asp:ImageButton ID="Submit" runat="server" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" OnClientClick="submitClicked" />
The purpose of that event is for submitting all the values in the form to database.Here my problem is,After adding the onClick event to button, validation has not taken place.And i want these onClick event to raise only when the form is validated successfully.Can any one guide me ..Thanks in Advance.
make sure that you are using the same validation group for all the validation controls.
in addition you can use OnClientClick event to call validation.
<asp:ImageButton ID="Submit" runat="server" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" OnClientClick="return Page_ClientValidate('AddSchoolValidationGroup');" />
You need to validate the page before submitting. Please add attribute for button.
protected void Page_Load(object sender, EventArgs e)
{
Submit.Attributes.Add("onclick", "javascript:if(Page_ClientValidate('AddSchoolValidationGroup')){return true;}else{return false;}");
}
Since you have a method "submitClicked" in onclient click, you can call the same inside Page_ClientValidate and remove the existing "OnClientClick" property.
protected void Page_Load(object sender, EventArgs e)
{
Submit.Attributes.Add("onclick", "javascript:if(Page_ClientValidate('AddSchoolValidationGroup')){submitClicked(); return true;}else{return false;}");
}
You can use javascript function
function validateForm() {
if (document.getElementById('txtName').value == '')
{
ValidatorEnable(document.getElementById("rfvName"), true) // rfvName is id of validator
return false; }
}
and call that function on client click of image button
<asp:ImageButton ID="Submit" runat="server" OnClientClick="validateForm();" OnClick="submit_Clicked" ValidationGroup="AddSchoolValidationGroup" CausesValidation="true" ImageUrl="~/Styles/images/submit-btn.png" />
Replace OnClientClick="submitClicked" with OnClientClick="return submitClicked();"
function submitClicked()
{
if (document.getElementById('txtname') != '') {
return true;
}
else {
alert('Please Enter Name');
return false;
}
}
So until all the validations are validated, the Server side event will not be called.

Clicking on cancel on Javascript Confirm box does not stop the grid from refreshing

How to stop the page from rendering the .cs code on click of cancel button on javascript confirm box?
I have a button click event and in some IF condition I am asking the user to confirm. Now when the user clicks on OK button, I have to bind the new data in a grid. but if the user clicks on cancel button, it should not refresh the grid with new data.
Question: On click of cancel button on JavaScript confirm box, how can I stop the following code to be executed, or how can I just return/break from JavaScript?
Can anyone please help me out with this? Thanks in advance.
Markup
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="false" OnClick="btnCopy_Click" ValidationGroup="Copy" />
Code
public void btnCopy_Click(object sender, EventArgs e) {
if (Convert.ToInt32(hidId.Value) > 0) {
string scriptString = "<script language='JavaScript'> ";
scriptString += "if (confirm('Are you sure to proceed?') == false) {return} ";
scriptString += "</script>";
Page.RegisterStartupScript("Confirm", scriptString);
BindDataGrid();
}
}
You are mixing server and client side code in the same event, it has to be separated:
Script:
function Confirm()
{
var record=confirm('Are you sure to proceed??');
if(record == 1)
{
return true;
}
else if(record == 0)
{
return false;
}
}
Markup:
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="false"
OnClick="btnCopy_Click" OnClientClick='return Confirm();' ValidationGroup="Copy" />
Code-behind:
public void btnCopy_Click(object sender, EventArgs e) {
if (Convert.ToInt32(hidId.Value) > 0) {
BindDataGrid();
}
}
You'll need to catch the response, for example:
if (window.confirm)
{
//handle the OK
}
else
{
//handle the cancel
}
Please show the code, but without seeing your code I would guess you are not returning the response?
<input type="button" onclick=" return confirm('is this right?'); ">
You can simply return from the code or exit(0).
function fillGrid()
{
if( confirm("....") )
{
//populate your grid
}
else
{
return;
}
//do anything after the grid is populated
//and exit the function
}
You are showing the confirm dialog in the codebehind of your button click, that wont stop the flow of your code.
You need to show the confirm dialogbox before do the postback
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="true" OnClientClick="return confirm('sure?');" ValidationGroup="Copy" />

Categories

Resources