Inquiridor
Desabilitar Button até o fim do metodo!

Pergunta
-
Pessoal estou com um problema após um event_click de um button em aspx; Quando clico no button ele passa por varios metodos até concluir tudo que precisa, o problema que se a conexão for lenta o usuário acaba clicando varias vzs no button fazendo assim inserções duplicadas pois ele salva oq esta na tela. O que eu preciso é após entrar no event_click do button o button na página aspx fica desabilitado até termina-lo. Mesmo usando ajax com updatepanel e updateprohress ocorre alguns cassos q o user clica varias vzs criando inserções duplicadas. Por isso preciso tratar isso no C# ou se tiver outra forma melhor me avisem.
protected void btnSaveNoParcel_Click(object sender, ImageClickEventArgs e) { try { //quando for aluno if (rbEmployee.SelectedIndex == 0) { decimal dec; if (txtDiscount.Text == "") { dec = 0; } else { dec = decimal.Parse(txtDiscount.Text); } if (decimal.Parse(txtBalance.Text) < 0 || dec > decimal.Parse(txtValue.Text)) { Master.SetMessage( "Valor do Saldo não pode ser negativo nem o Desconto ser maior que o valor da excursão!", "~/imagens/erro/erro.png"); } else { # region SaveObjects //btnSaveNoParcel.Visible = false; #region traveller //Cria participante //IB.Student objST = IB.Student.ListUserStudentFullItem(int.Parse(ddlSite.SelectedValue), // int.Parse(txtStudentCode.Text)); IB.Student objST = IB.Student.ListStudentInTourClass(int.Parse(ddlSite.SelectedValue), int.Parse(ddlSchool.SelectedValue), int.Parse(ddlTour.SelectedValue), int.Parse(txtStudentCode.Text)); int TravellerID = 0; if (hfTraveller.Value != "") TravellerID = int.Parse(hfTraveller.Value); IB.Traveler objT = new IB.Traveler(int.Parse(ddlSite.SelectedValue), int.Parse(ddlSchool.SelectedValue), int.Parse(ddlTour.SelectedValue), TravellerID, 1, objST.StudentID, objST.Name, objST.ClassID, objST.SerieID, objST.DateBirth, objST.UserName, objST.CPFGuardian, objST.NumberCardIdentity, objST.CPFGuardian, true); IB.Traveler.Save(objT); int _TravellerID = objT.TravelerID; #endregion #region Payment //Pagamento int PaymentID = 0; if (hfPayment.Value != "") PaymentID = int.Parse(hfPayment.Value); decimal disc = 0; if (txtDiscount.Text != "") disc = decimal.Parse(txtDiscount.Text); decimal value = decimal.Parse(txtBalance.Text); //if (disc > 0) //{ // value = decimal.Parse(txtValue.Text) - decimal.Parse(txtDiscount.Text); // txtPayValue.Text = value.ToString("#,##0.00"); //} IB.Payment objP = new IB.Payment(PaymentID, int.Parse(ddlTour.SelectedValue), _TravellerID, value, disc); IB.Payment.Save(objP); int _PaymentID = objP.PaymentID; #endregion #region CurrentAccount //criando conta corrente int CurrentAccountID = 0; if (hfCurrentAcount.Value != "") CurrentAccountID = int.Parse(hfCurrentAcount.Value); IB.CurrentAccount objC = new IB.CurrentAccount(CurrentAccountID, _PaymentID, int.Parse(ddlTour.SelectedValue), _TravellerID, value, 1, txtDescriptionNoParcel.Text, DateTime.Parse(txtDate.Text)); IB.CurrentAccount.Save(objC); #endregion #region moviment //Cria movimento int MovementID = 0; IB.Movement oldMov = IB.Movement.MovementItem(int.Parse(ddlTour.SelectedValue), _TravellerID); if (oldMov != null) { decimal mov = value - oldMov.Value; IB.Movement objMov = new IB.Movement(MovementID, int.Parse(ddlTour.SelectedValue), _TravellerID, int.Parse(txtPayValue.Text), DateTime.Now, mov); IB.Movement.Save(objMov); } else { IB.Movement objMov = new IB.Movement(MovementID, int.Parse(ddlTour.SelectedValue), _TravellerID, value, DateTime.Now, value); IB.Movement.Save(objMov); } #endregion #endregion # region Receipt if (ckNReceipt.Checked) { //Impressão do recibo if (rbReportType.SelectedIndex == 0) { string url = "/treasury/tour/payment/reciboA4.aspx?tourid=" + ddlTour.SelectedValue + "&travelerid=" + _TravellerID + "&obs=" + txtDescriptionNoParcel.Text + "&vpay=" + txtPayValue.Text + "&spay=" + txtBalance.Text; HttpContext.Current.Response.Write("<script>window.open('" + url + "','_blank');</script>"); // crReportDocument.Load(Server.MapPath("/treasury/tour/payment/reciboA4.rpt")); } else { string url = "/treasury/tour/payment/recibo.aspx?tourid=" + ddlTour.SelectedValue + "&travelerid=" + _TravellerID + "&obs=" + txtDescriptionNoParcel.Text + "&vpay=" + txtPayValue.Text + "&spay=" + txtBalance.Text; HttpContext.Current.Response.Write("<script>window.open('" + url + "','_blank');</script>"); /// crReportDocument.Load(Server.MapPath("/treasury/tour/payment/recibo.rpt")); } } //ReportDocument crReportDocument = new ReportDocument(); //dsReceipt dsReport = new dsReceipt(); //dsReport.dtTravellerReceipt.Merge(IB.Traveler.ListDTtraveller(int.Parse(ddlTour.SelectedValue), // _TravellerID)); //if (rbReportType.SelectedIndex == 0) //{ // crReportDocument.Load(Server.MapPath("reciboA4.rpt")); //} //else //{ // crReportDocument.Load(Server.MapPath("recibo.rpt")); //} //crReportDocument.SetDataSource(dsReport); //C.RelatorioCrystal.SetParameter("obs", crReportDocument, txtDescriptionNoParcel.Text); //if (txtPayValue.Text != "") //{ // C.RelatorioCrystal.SetParameter("Pay", crReportDocument, txtPayValue.Text); //} //else //{ // C.RelatorioCrystal.SetParameter("Pay", crReportDocument, txtBalance.Text); //} //impressão direta do .rpt sem conversão // crReportDocument.PrintToPrinter(1, true, 0, 0); # endregion lbNoParcelMessage.Text = "Itens salvos com sucesso!"; CleanNoparcel(); } } else { # region SaveObjects #region traveller //Cria participante funcionário/professor IB.Employee objST = ReturnEmployee(); int TravellerID = 0; if (hfTraveller.Value != "") TravellerID = int.Parse(hfTraveller.Value); IB.Traveler objT = new IB.Traveler(int.Parse(ddlSite.SelectedValue), int.Parse(ddlSchool.SelectedValue), int.Parse(ddlTour.SelectedValue), TravellerID, 2, int.Parse(objST.Code), objST.Name, "P/F", 0, objST.Birth, "", objST.CPF, "", objST.CPF, true); IB.Traveler.Save(objT); int _TravellerID = objT.TravelerID; #endregion #region Payment //Pagamento int PaymentID = 0; if (hfPayment.Value != "") PaymentID = int.Parse(hfPayment.Value); decimal disc = 0; if (txtDiscount.Text != "") disc = decimal.Parse(txtDiscount.Text); decimal value = decimal.Parse(txtPayValue.Text); //if (disc > 0) //{ // value = decimal.Parse(txtValue.Text) - decimal.Parse(txtDiscount.Text); // txtPayValue.Text = value.ToString("#,##0.00"); //} IB.Payment objP = new IB.Payment(PaymentID, int.Parse(ddlTour.SelectedValue), _TravellerID, value, disc); IB.Payment.Save(objP); int _PaymentID = objP.PaymentID; #endregion #region CurrentAccount //criando conta corrente int CurrentAccountID = 0; if (hfCurrentAcount.Value != "") CurrentAccountID = int.Parse(hfCurrentAcount.Value); IB.CurrentAccount objC = new IB.CurrentAccount(CurrentAccountID, _PaymentID, int.Parse(ddlTour.SelectedValue), _TravellerID, value, 1, txtDescriptionNoParcel.Text, DateTime.Parse(txtDate.Text)); IB.CurrentAccount.Save(objC); #endregion #endregion # region Receipt if (ckReceipt.Checked) { //Impressão do recibo ReportDocument crReportDocument = new ReportDocument(); dsReceipt dsReport = new dsReceipt(); dsReport.dtTravellerEmp.Merge(IB.Traveler.ListDTtravellerEmployee(int.Parse(ddlTour.SelectedValue), _TravellerID)); if (rbReportType.SelectedIndex == 0) { crReportDocument.Load(Server.MapPath("reciboPFA4.rpt")); } else { crReportDocument.Load(Server.MapPath("reciboPF.rpt")); } crReportDocument.SetDataSource(dsReport); C.RelatorioCrystal.SetParameter("obs", crReportDocument, txtDescriptionNoParcel.Text); C.RelatorioCrystal.SetParameter("Pay", crReportDocument, txtPayValue.Text); //impressão direta do .rpt sem conversão crReportDocument.PrintToPrinter(1, false, 0, 0); } # endregion } } catch (Exception ex) { Master.SetMessage(ex.Message, "~/imagens/erro/erro.png"); } }
Moizés Cerqueira | MCP / MCTS SQL SERVER
Todas as Respostas
-
Olá tente fazer por javascript
no incio do metodo chame o javascript
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowButton", "DesabilitarBotao();", true);
e no final chame novamente para habilitar
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "HideButton", "HabilidatBotao();", true);
script
DesabilitarBotao = function () {
var bo = document.getElementById("<%=Button1.ClientID%>");
if (bo != null) {
bo.disable=true;
}
};acho que é isso!
-
Ola,
Fazer isso no server-side parece ser improvável, pois ate a pagina realizar o processamento e redenrizar, o usuário já terá realizados vairos clicks...
O que você pode fazer é desativar o botão via javascript e ai reabilitar pelo server-side ao final do processo.
<%@ Page Language="C#" AutoEventWireup="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(3000); concluidoLabel.Visible = true; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function disableButton(sender) { sender.disabled = true; sender.value = "Aguarde..."; return true; } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button UseSubmitBehavior="false" ID="enviarButton" runat="server" Text="Enviar..." OnClientClick="disableButton(this);" OnClick="Button1_Click" /> <asp:Label ID="concluidoLabel" runat="server" Text="Processo Concluido!" Visible="False"></asp:Label> </div> </form> </body> </html>
Microsoft Community Contributor
- Editado Rui SantosModerator terça-feira, 13 de agosto de 2013 20:49
-
Carlos tentei usar desta forma porém coloquei um sleep pra deixar em espera após chamar o script de que desabilita o button porém não funcionou mesmo após passar pelo método que executa o script de desabilitar eu ainda consigo clicar varias vzs no button.
try { System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowButton", "DesabilitarBotao();", true); System.Threading.Thread.Sleep(3000); loader.Visible = true; IB.Traveler V_trav = IB.Traveler.ListTravelerVerific(int.Parse(ddlSite.SelectedValue), int.Parse(ddlSchool.SelectedValue), int.Parse(ddlTour.SelectedValue), int.Parse(txtStudentCode.Text)); System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowButton", "DesabilitarBotao();", false); loader.Visible = false; }
Moizés Cerqueira | MCP / MCTS SQL SERVER
-
Rui, tentei usar estes scripts porém ele desabilita o button no click e não entra no event_click do button no c#, será que fiz algo errado?
<script runat="server"> protected void Button1_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(3000); loader.Visible = true; } </script> <script type="text/javascript"> function disableButton(sender) { sender.disabled = true; sender.value = "Aguarde..."; return true; } </script>
<asp:ImageButton ID="btnSaveNoParcel" runat="server" ImageUrl="~/imagens/save_tour.png" OnClientClick="disableButton(this);" OnClick="btnSaveNoParcel_Click" ValidationGroup="vsNoParcel" />
Moizés Cerqueira | MCP / MCTS SQL SERVER
-
Como voce está usando ImageButton, tente remover o evento de Click.
Exemplo via jQuery:
// Nome do evento do ImageButton var clickEvent = "btnSaveNoParcel_Click"; function disableButton() { // Desabilita o botao $('<%= btnSaveNoParcel.ClientID %>').on("click", function(){ return false }); }); function enableButton() { $('<%= btnSaveNoParcel.ClientID %>').on("click", function(){ clickEvent }); });
Abraços,
Washington Luíz | MCP, MCTS
O Senhor é minha força e somente Nele confio.- Editado Washington sexta-feira, 16 de agosto de 2013 14:18
-
Washington, obrigado pela dica mas não conheço muito de jquery é dessa forma que implemento?
<asp:ImageButton ID="btnSaveNoParcel" runat="server" ImageUrl="~/imagens/save_tour.png" OnClientClick="disableButton()" ValidationGroup="vsNoParcel" />
<script type="text/javascript"> // Nome do evento do ImageButton var clickEvent = "btnSaveNoParcel_Click"; function disableButton() { // Desabilita o botao $('<%= btnSaveNoParcel.ClientID %>').on("click", function(){ return false }); }); function enableButton() { $('<%= btnSaveNoParcel.ClientID %>').on("click", function(){ clickEvent }); }); </script>
Moizés Cerqueira | MCP / MCTS SQL SERVER
-
Olá Moizés.
Voce precisa incluir o script do jQuery em sua aplicação para que o codigo acima funcione ok?
A implementação é do jeito que voce disse mesmo, só lembrando que nao precisa setar o evento OnClientClick no seu controle.
<asp:ImageButton ID="btnSaveNoParcel" runat="server" ImageUrl="~/imagens/save_tour.png" ValidationGroup="vsNoParcel" />
Washington Luíz | MCP, MCTS
O Senhor é minha força e somente Nele confio. -
Ola Moises.
Primeiramente, o server-side (evento click) só vai ser executado no final do processo.... portanto se quiser deixar algo visivel, tem que ser feito dentro do metodo javascript disableButton...
Que seria algo mais ou menos assim:
<%@ Page Language="C#" AutoEventWireup="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(3000); concluidoLabel.Visible = true; loader.Style["display"] = "none"; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function disableButton(sender) { sender.disabled = true; sender.value = "Aguarde..."; var loader = document.getElementById("<%= loader.ClientID %>"); loader.style.display = "block"; return true; } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button UseSubmitBehavior="false" ID="enviarButton" runat="server" Text="Enviar..." OnClientClick="disableButton(this);" OnClick="Button1_Click" /> <asp:Label ID="concluidoLabel" runat="server" Text="Processo Concluido!" Visible="False"></asp:Label> <div id="loader" runat="server" style="display: none"> Carregando... </div> </form> </body> </html>
Microsoft Community Contributor
-
Continuando,
Não sei porque, mas o ImageButton não rendereiza o metodo __doPostBack, mas isso da para ser corrigido da seguinte maneira:
<asp:ImageButton ID="enviarImageButton" runat="server" OnClientClick="disableButton(this);__doPostBack('enviarImageButton','')" OnClick="Button1_Click" PostBackUrl="~/WebForm1.aspx" />
Microsoft Community Contributor
-
Como voce está usando ImageButton, tente remover o evento de Click.
Exemplo via jQuery:
// Nome do evento do ImageButton var clickEvent = "btnSaveNoParcel_Click"; function disableButton() { // Desabilita o botao $('<%= btnSaveNoParcel.ClientID %>').on("click", function(){ return false }); }); function enableButton() { $('<%= btnSaveNoParcel.ClientID %>').on("click", function(){ clickEvent }); });
Abraços,
Washington Luíz | MCP, MCTS
O Senhor é minha força e somente Nele confio.
Washington,
Acredito que voce esta se confundindo... o evento Onclick aqui é server-side e não Client-side.... nesse caso o jQuery não solucionaria o problema.
Microsoft Community Contributor
-
Washington, eu coloquei o script na págin aspx dentro de
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
Onde utilizo os jscripsts, ele habilita e desabilita o imagebutton porém não chama o evento veja como fiz:<script type="text/javascript"> // Nome do evento do ImageButton var clickEvent = "btnSaveNoParcel_Click"; function disableButton() { // Desabilita o botao $('<%= btnSaveNoParcel.ClientID %>').on("click", function() { return false }); }; function enableButton() { $('<%= btnSaveNoParcel.ClientID %>').on("click", function() { clickEvent }); }; </script>
e meu imageButton Drixei Assim:
<asp:ImageButton ID="btnSaveNoParcel" runat="server" ImageUrl="~/imagens/save_tour.png" ValidationGroup="vsNoParcel" />
Que deve chamar o evento:
protected void btnSaveNoParcel_Click(object sender, ImageClickEventArgs e)
Moizés Cerqueira | MCP / MCTS SQL SERVER
-
-