Disable a button server side - asp.net

I have a form with a submit button which I want to disable upon submitting (so the user does not submit the form content twice).
The form has 2 mandatory fields that should be filled in, so an easy on click disable button (client-side) will not do the trick i'm afraid.
Protected Sub Btn_SubmitContact_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Btn_SubmitContact.Click
If Page.IsValid Then
Btn_SubmitContact.Enabled = False
//all other logic
End If
End Sub
This does not change the attribute of the key, the user can still click the button and post the content twice. I understand that some refresh/update needs to happen for the button to change...
Can someone please explain me how this works?

First check the mandatory fields with asp:RequiredFieldValidator and then when the button is clicked you can disable it with Javascript:
<asp:button id="Btn_SubmitContact"
OnClientClick="this.disabled = true; this.value = 'In process...';"
UseSubmitBehavior="false" OnClick="Btn_SubmitContact_Click"
Text="Submit" runat="server" />

Related

Transfer radio button from webform to another form using VB.net and ASP.net

I wrote the below code which transfer the radio button value and check box value to another HTML form but i did not find solution to transfer the radio button or check box at all to another form not only the selected value.
I want the radio button to be transfered to another form as below not only the value.
enter image description here
Dim Gender As String = RadioButton1.SelectedValue
Response.Redirect("PrintPreview.aspx?"&Gender=" + Gender)
Label1.Text = Request.QueryString("Gender")
The code only returned the radio button value
Please advise
Ok, the FIRST thing, and MOST important thing to realize here is that when you execute a response.Redirect ?
It STOPS code running in the current page.
No code AFTER the Response.Redirect will run
All variables, and code and ALL values for the current page are destroyed!
So, you can't write (normally) code to run after the response.Redirect.
So, say we have this markup:
<br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
Font-Size="Larger" RepeatDirection="Horizontal">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="Button1" runat="server" Text="Done" />
And our page now looks like this:
Now, we want to jump to page 2.
So our code can say look like this in our Test1 page.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Gender As String = RadioButtonList1.SelectedItem.Text
Response.Redirect("Test2.aspx?&Gender=" & Gender)
' code AFTER above line WILL NOT run!!!!
End Sub
So, we can't have code AFTER the response.Redirect.
Again, read this 5 times:
when the response.Redirect is used, then the current page code STOPS,
and ALL values, and even your code variables are DESTROYED!!! This is not much
different then when you get to the end of a subroutine - when you exit, then all
values and things in that subroutine are "gone", and "do not exist".
The same goes for your web page - using Response.Redirect means STOP code, transfer to another page.
So, now above will jump to page Test2, we want to take that value we passed, and do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' save a label on this page to the passed choice
Label1.Text = Request.QueryString("Gender")
End If
End Sub
Also, note close your syntax for the string you were passing in Response.Redirect was also incorrect.

Double clicking fire of dynamically generated web controls

Dynamic button controls in a panel existing. Clicking on specific button needs to be disabled while the event is firing to prevent double click submission. Can any one suggest me some ideas? Thanks in advance.
To Use in HTML:
<asp:LinkButton Style="color: red; font-family: verdana" runat="server" ID="LinkEliminar">Eliminar</asp:LinkButton>
To Use in ASPX
Protected Sub LinkEliminar_Click(sender As Object, e As EventArgs) Handles LinkEliminar.Click
Label16.Text = "¿Eliminar Requisición No." & Label14.Text & "?.-"
eliminar.Visible = True
End Sub

I would like to trigger an event when a checkbox is clicked

Private Sub ShowPasswordButton_CheckedChanged(sender As Object, e As EventArgs) Handles ShowPasswordButton.CheckedChanged
If ShowPasswordButton.Checked = True Then
NewPassword.TextMode = TextBoxMode.SingleLine
Else
NewPassword.TextMode = TextBoxMode.Password
End If
End Sub
I am trying to change text appearance when the box is checked, but checking the box does nothing. It doesn't trigger the event at all. I have this placed in the right spot and I would assume that it should run, but it isn't.
You should have the AutoPostBack="True" property in your checkbox to trigger a server side event.

Disabled asp.net button disables validation for button

I have an aspx page that contains a checkbox, and a button. The button is disabled by default until the user checks the checkbox. It looks like when I add the attribute enabled="false" to the button, it removes the validation. When the button is enabled, I still want the validation to work. Here is the code and markup for the different parts.
Checkbox:
<asp:CheckBox runat="server" ID="termsCheckBox" />
<label style="display: inline;">
I agree to the Terms & Conditions</label>
Button:
<asp:Button runat="server" ID="registerButton" OnClick="registerButton_Click1"
Text="Register" Enabled="false" ValidationGroup="accountValidation" />
JQuery:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#<%=termsCheckBox.ClientID %>').click(function () {
var checked = $(this).val();
if (checked != undefined)
$('#<%=registerButton.ClientID %>').removeAttr('disabled');
else
$('#<%=registerButton.ClientID %>').attr('disabled', 'disabled');
});
});
</script>
It seems like the validation should be attached to the checkbox, not the button.
Asp.net is stupid because when a control is disabled, there's all sorts of stuff that won't happen with it.
In this case, the js code to cause client side validation will not be created for a disabled button.
If you try to manually add in the clientside js code from the code behind,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
registerButton.OnClientClick = String.Format("javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('{0}', '', true, '', '', false, false))", registerButton.UniqueID)
End Sub
It will not work because asp.net will not render all the attributes for a disabled control.
There are two solutions then. Either disable the control with JS at client side or add the javascript to perform a postback with validation at client side.
What I did for my program was to add code to create js code to disable the button at the client side:
If btnSubmit.Enabled = False Then
'Asp.net will not render all the attributes for a control that is disabled. Even if you
'try to set the OnClientClick attribute manually in code behind for the control, it will
'not work. Asp.net will not render the attribute. This is a workaround for this problem.
btnSubmit.Enabled = True
strJavaScript &= "btnSubmit.disabled = true;"
End If
ClientScript.RegisterStartupScript(Page.GetType(), "myStartupScript", strJavaScript, True)
Note that btnSubmit is a javascript variable that is already defined in my client side code.
I think it would work if you enabled/disabled the button on the checkBox server-side event rather than client side since the associated client-side validation code will be generated to run for ValidationGroup of the button

Help with DataGrid/CheckBoxes/double submit

We have a simple datagrid. Each row has a checkbox. The checkbox is set to autopostback, and the code-behind has an event handler for the checkbox check-changed event. This all works as expected, nothing complicated.
However, we want to disable the checkboxes as soon as one is checked to prevent a double submit i.e. check box checked, all checkboxes are disabled via client side javascript, form submitted.
To achieve this I we are injecting some code into the onclick event as follows (note that the alert is just for testing!):
Protected Sub DgAccounts_ItemCreated(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DgAccounts.ItemCreated
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim chk As CheckBox = CType(e.Item.FindControl("chkItemChecked"), CheckBox)
chk.Attributes.Add("onclick", "alert('fired ...');DisableAllDataGridCheckBoxes();")
End If
End Sub
When inspecting the source of the rendered page we get the following:
<input id="DgAccounts__ctl2_chkItemChecked" type="checkbox" name="DgAccounts:_ctl2:chkItemChecked" onclick="alert('fired ...');DisableAllDataGridCheckBoxes();setTimeout('__doPostBack(\'DgAccounts$_ctl2$chkItemChecked\',\'\')', 0)" language="javascript" />
It all appears in order, however the server side event does not fire – I believe this is due to the checkbox being disabled, as if we just leave the alert in and remove the call to disable the checkbox it all works fine.
Can I force the check-changed event to fire even though the check box is disabled?
I haven't tested this myself but when you call your 'DisableAllDataGridCheckBoxes' method, do you need to disable the checkbox that has been checked?
If not, you could pass the calling checkbox's id and then only disable all the other checkboxes.
chk.Attributes.Add("onclick", "alert('fired ...');DisableAllDataGridCheckBoxes(" + chk.ClientId + ");")
I would think this would then allow the server side code to fire.
The reason the server side event is not firing is that disabled checkboxes do not get submited with the rest of the form.
The workaround I have used is to set the onclick event of the checkboxes to null rather than disable them - while this gives no visual clue to the user that subsequent clicks are ignored, it does prevent the double submit, and the check boxes are set top the correct state when the response is rendered.
Instead of disabling the checkboxes (which then do not get submitted), just "prevent" them from being selected. Do this by changing their onclick handler to reset the checked state. You coul dset all of the other checkboxes to disabled, and do this just for the one that is processing. Something like:
function stopChanges(cbCurrent) {
$('INPUT[type=checkbox]').disable(); // disable all checkboxes
$(cbCurrent)
.disable(false) // enable this checkbox, so it's part of form submit
.click(function() {
// reset to previous checked - effectively preventing change
$(this).checked = !$(this).checked;
}
);
}
A possible workaround, would be to do all this in the server side code of the RowCommand of the data grid.
(posting the sample in C# but won't be much different in VB I hope)
protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(((CheckBox)e.Item.FindControl("chkItemChecked")).Checked)
{
foreach(GridViewRow dvRow in myGrid.Rows)
((CheckBox)dvRow.FindControl("chkItemChecked")).Enabled = false;
}
}
or you could use
((CheckBox)e.Item.FindControl("chkItemChecked")).Enabled = false;
if you only want to disable the specific item.
However if you only want to implement this in client side code, it won't help you.

Resources