ASP disable button during postback - c#

I have a button which i am trying to add a css class to appear disabled once the user has clicked it.
protected void Button_Continue_OnClick(object sender, EventArgs e)
{
Panel_Error.Visible = false;
Literal_Error.Text = "";
if (RadioButton_Yes.Checked)
{
...//if radio checked get text and process etc.
}
}
My button onlick is above which simply processes a textbox filled on the page.
My button looks like this:
<asp:Button runat="server" ID="Button_Continue" CssClass="button dis small" Text="Continue" OnClick="Button_Continue_OnClick" ClientIDMode="Static" OnClientClick="return preventMult();" />
And my javscript is as follows:
<script type="text/javascript">
var isSubmitted = false;
function preventMult() {
if (isSubmitted == false) {
$('#Button_Continue').removeClass('ready');
$('#Button_Continue').addClass('disabled');
isSubmitted = true;
return true;
}
else {
return false;
}
}
</script>
The problem I am having is that the css class added works fine on the first postback, but after which my button onclick doesnt work and the button cant be clicked again if the user needs to resubmit the data if it is wrong
Another problem I am having is that with a breakpoint in my method i notice that the method is fired twice on the click.

Looks like you need something like this:
private void Page_Load()
{
if (!IsPostBack)
{
//doNothing
}
else
{
//button.disabled = true
}
}

try this
<asp:Button runat="server" ID="Button_Continue" AutoPostBack="true" CssClass="button dis small" Text="Continue" OnClick="Button_Continue_OnClick" ClientIDMode="Static" OnClientClick="return preventMult();" />

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;

how to close radwindow in asp.net?

I am a using ASP.NET controller to display user detail. When RadWindow is open & I tried to close with Close button. But the problem is that after page load and post back it opens again and again. I've multi-option on page: new, save, print etc. search.
<telerik:RadWindow ID="rwReport" runat="server" Behaviors="Close" KeepInScreenBounds="true"
AutoSize="true" VisibleOnPageLoad="false" Modal="true" Title="Report ACMI Advance Payment"
DestroyOnClose="true">
<ContentTemplate>
<ucRPV:ReportViewer id="ucReportViewer" runat="server" />
</ContentTemplate>
</telerik:RadWindow>
cs file code
private void Print()
{
try
{
// this.sADPs.DisplayReport();
Hashtable reportParameters = new Hashtable();
reportParameters.Add("DataSourceName", "dsACMIAdvancePayment");
reportParameters.Add("reportName", "rptACMIAdvancePayment.rdlc");
reportParameters.Add("Id", this.hfId.Value.ToString().ConvertTo<long>());
this.ucReportViewer.clearReport();
this.ucReportViewer.showReport(reportParameters);
this.rwReport.VisibleOnPageLoad = true;
//showReport(reportParameters);
}
catch(Exception e)
{
throw e;
}
}
ASPX code:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxControlToolkit" %>
<%# Register Src="../Reports/rpvReportViewerPopup.ascx" TagName="ReportViewer" TagPrefix="ucRPV" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%# Register Src="../Common/UserControls/ToolBarActions.ascx" TagName="ToolBarActions" TagPrefix="ucTBA" %>
</td>
Do not use the VisibleOnPageLoad property to show a RadWindow, register a script that will call its show() method. Thus, subsequent postbacks will not cause it to show up by itself: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-opening-from-server.html.
Of course, preventing the form from re-submitting as Felice suggested is another thing that may also be needed.
To translate this into code:
instead of:
this.rwReport.VisibleOnPageLoad = true;
use:
string script = "function f(){$find(\"" + rwReport.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
You can try below code : this might help-
<telerik:RadScriptBlock runat="server" ID="scriptBlock">
<script type="text/javascript">
//<![CDATA[
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseWin() {
//Get the RadWindow
var oWindow = GetRadWindow();
//Call its Close() method
if (oWindow) {
oWindow.Close();
}
return false;
}
</script>
</telerik:RadScriptBlock>
And on Page: yourpage.aspx;... call the function onClientClick of button:
<asp:Button ID="btnClose" Text="Close" runat="server" CssClass="button" Enabled="true" OnClientClick="CloseWin();" />
I have experienced the same problem when you reload the page because the browser resend the information and the radwindow opens again. To avoid such behavior I have adopted the following solution:
Add a hidden filed to hold the client code:
<asp:HiddenField runat="server" ID="_repostcheckcode" />
Add the following code in the code page:
protected void Page_Load(object sender, EventArgs e)
{
CancelUnexpectedRePost();
}
private void CancelUnexpectedRePost()
{
string clientCode = _repostcheckcode.Value;
//Get Server Code from session (Or Empty if null)
string serverCode = Session["_repostcheckcode"] as string ?? "";
if (!IsPostBack || clientCode.Equals(serverCode))
{
//Codes are equals - The action was initiated by the user
//Save new code (Can use simple counter instead Guid)
string code = Guid.NewGuid().ToString();
_repostcheckcode.Value = code;
Session["_repostcheckcode"] = code;
}
else
{
//Unexpected action - caused by F5 (Refresh) button
Response.Redirect(Request.Url.AbsoluteUri);
}
}
The original article can be found here.
Add a Button with an OnClick handler with the following code:
protected void CloseRadWindow(object sender, EventArgs e)
{
rwReport.VisibleOnPageLoad = false;
}

How to prevent postback on asp button while displaying a popup using JQuery

I have the following ItemTemplate in my GridView:
<ItemTemplate>
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnClientClick="myfunction(); return false;" OnCommand="btnShow_Command" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' />
</ItemTemplate>
For the ItemTemplate I have a button which opens a popup window when clicked by using the following JQuery:
$(document).ready(function () {
$(".btnSearch").click(function (e) {
e.preventDefault();
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
function myfunction() {
}
my Command code-behind:
protected void btnShow_Command(object sender, CommandEventArgs e)
{
int index = 0;
if (e.CommandName == "ViewAll")
{
index = Convert.ToInt32(e.CommandArgument);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
//tbGL.Text = html;
//upData.Update();
//MessageBox.Show(index.ToString());
}
}
I added the OnClientClick="myfunction(); return false;" because it was doing a postback each time I clicked. If I have multiple rows, it only works the first time I click but any time after, the popup is not displayed when another or the same button is clicked.
How do I resolve it so no matter which button is clicked the popup is displayed without doing a postback?
Actually you have not showed up the implementation of your method myfunction(), in case the myfunction() method have any syntactical error then the OnClientClick event will be void and it will post-back/submit the form to the server.
Try to remove the call from OnClientClick and just implement your logic at jquery on click event by using class selector as follows
$(document).ready(function () {
$(".btnSearch").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked"); // you can put your method mymethod() here
// you can put youe popup logic here
return false;
});
});
You can also see this example of js fiddle
Put it out on the tag or <%: Html.BeginForm %> tag
OnClientClick="return myfunction();
function myfunction(){
// you can put youe popup logic here
return false;
}
Using like this your button never do post back.

how to call an alert box in code behind on button click in?

I have a button , When Clicks on it , I have to generate an alert box with "Ok" "Cancel" button. I have done like this, script on .aspx is,
<script>
function getConfirmationValue2()
{var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value2";
if (confirm("Save??")) {
confirm_value.value = "OK";
} else {
confirm_value.value = "CANCEL";
}
document.forms[0].appendChild(confirm_value);
} </script>
<asp:ImageButton ID="btn_submit" runat="server" ImageUrl="~/images/BtnSubmit.png" CausesValidation="true"
onclick="btn_submit_click"/>
on button click,
protected void btn_submit_click(object sender, ImageClickEventArgs e)
{
if(TextBox1.Text="start")
{
btn_submit.OnClientClick = #"return getConfirmationValue2();";
string confirmValue122 = Request.Form["confirm_value2"];
if (confirmValue122 == "OK")
{
//updating the datas
}
}}}
It generates the alert box only when clicks two times on button. What will be the problem?
You need to bind it in markup of button like OnClientClick = "return getConfirmationValue2();"
Markup of button
<asp:ImageButton ID="btn_submit"
runat="server"
ImageUrl="~/images/BtnSubmit.png"
CausesValidation="true"
OnClientClick = "return getConfirmationValue2();" <== Added code here
onclick="btn_submit_click"/>
It generates the alert box only when clicks two times on button. What will be the problem?
OnClientClick is binded when you click for first time, thus you are not getting alert box for first click.
If You want to register it in CodeBehind, I would suggest you to use Control.Init event or Page_Load event

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