button inside modal loads the page even if validations fire - asp.net

I have a form inside which I have a button1 which triggers the modal.
Inside modal window I have textboxes(to take some credentials) with validations and another button (button2) (type=button) containing onClick definition which is working fine if I provide good data, but when I provide no data in one of the text boxes and click on the button2 the complete page reloads and I get to my main page where I click on button1 and I see the validation messages.
The validation should appear just as the user clicks button2
I have looked around and tried couple of thing but cant figure out why is it happening,
I am using page routing in page_load is that the reason?
here is the code inside the modal in my html.aspx:
<form=from1 runat=server>
<div class="modal fade" id="logger_modal" tabindex="-1" role="dialog" aria-labelledby="logger_model1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body align-content-center">
<asp:TextBox ID="textbox1" runat="server" Class="form-control" placeholder="sometext" onkeydown = "return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="message1" ControlToValidate="textbox1" EnableClientScript="false" Display="Dynamic" ></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server" Class="form-control" placeholder="sometext" onkeydown = "return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="message2" ControlToValidate="textbox2" EnableClientScript="false" Display="Dynamic"></asp:RequiredFieldValidator>
</div>
<div class="modal-footer">
<asp:Button ID="close" runat="server" Text="Cancel" type="button" class="btn btn-secondary" data-dismiss="modal"/>
<asp:Button ID="button2" runat="server" Text="button2_text" type="button" class="btn btn-primary" CausesValidation="true" OnClick="OnClick_method" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</div>
</div>
</div>
Code inside ONClick_method in html.aspx.cs
if (Page.IsValid)
{
some code which works if i provide right values in textboxes
}
else
{
Label1.Text = "Please provide the details.";
}

This happens because your page does a postback and the page does a complete reload which results in closing the modal which causes probably the lose of values.
To prevent the page from completely reloading you can use a UpdatePanel for partial update of your page.
Example:
<div class="modal-body align-content-center">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="textbox1" runat="server" Class="form-control" placeholder="sometext" onkeydown="return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="message1" ControlToValidate="textbox1" EnableClientScript="false" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server" Class="form-control" placeholder="sometext" onkeydown="return (event.keyCode!=13);"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="message2" ControlToValidate="textbox2" EnableClientScript="false" Display="Dynamic"></asp:RequiredFieldValidator>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button2" />
</Triggers>
</asp:UpdatePanel>
</div>
You only surround the part that needs to be partially updated so the modal won't close and set the control for the async postback to button2.

Related

ASP.NET Update Panel - Required Field Validator fires for AutoPostBack DropDownList even though CausesValidation = false

I'm having an issue where a required field validator flashes on the screen when the dropdown list it's attached to does a partial postback on change.
Essentially the page is a form where the user selects from the 1st dropdownlist and that populates a second dropdownlist. They then select from the 2nd dropdownlist. Then when the user has selected both they hit the submit button and that validates both dropdowns.
Both dropdowns are in the validationgroup that the submit button uses. I've added CausesValidation="false" to the dropdownlist but the validator still flashes. Sample code below...
<form id="form1" runat="server">
<asp:ScriptManager ID="MyAppScriptManager" runat="server"
EnablePartialRendering="true"
EnableCdn="true" />
<div class="chat">
<asp:UpdatePanel ID="NewBookingUpdatePanel" UpdateMode="Conditional" ChildrenAsTriggers="true" runat="server">
<ContentTemplate>
<div id="FreelancerDiv" class="collapse show">
<div class="card-body">
<div class="form-group">
<div class="input-group">
<asp:DropDownList ID="FreelancerDropDownList" runat="server" AutoPostBack="true"
CausesValidation="false"
class="custom-select form-control form-control-lg">
<asp:ListItem Value=" " Text="Choose the freelancer for your booking." />
<asp:ListItem Value="Good" Text="Good selection." />
</asp:DropDownList>
</div>
<asp:RequiredFieldValidator ID="FreelancerRequired" runat="server" Display="Dynamic"
ControlToValidate="FreelancerDropDownList"
ValidationGroup="RequestBookingValidationGroup"
ErrorMessage=" Required "
CssClass="alert-danger" />
</div>
</div>
</div>
<div id="ServiceDiv" class="collapse show" runat="server">
<div class="card-body">
<div class="form-group">
<div class="input-group">
<asp:DropDownList ID="ServiceDropDownList" runat="server" AutoPostBack="true"
CausesValidation="false"
class="custom-select form-control form-control-lg">
<asp:ListItem Value=" " Text="Choose the service for your booking." />
<asp:ListItem Value="Good" Text="Good selection." />
</asp:DropDownList>
</div>
<asp:RequiredFieldValidator ID="ServiceRequired" runat="server" Display="Dynamic"
ControlToValidate="ServiceDropDownList"
ValidationGroup="RequestBookingValidationGroup"
ErrorMessage=" Required "
CssClass="alert-danger" />
</div>
</div>
</div>
<button id="RequestBooking" runat="server" class="btn btn-lg btn-primary btn-block" type="button" onserverclick="RequestBooking_Click" validationgroup="RequestBookingValidationGroup">
Request Booking
</button>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
You can enable or disable (enabled=true or enabled=false) the required field validators on the postback (and/or in the markup or page load event). Believe it's defaulted to enabled which is why its firing.
#JobesK thanks for Enabled=false tip that helped :)
I disabled the validators in markup and then enabled them in javascript in the submit button...
ValidatorEnable(document.getElementById('<%=FreelancerRequired.ClientID%>'), true);
ValidatorEnable(document.getElementById('<%=ServiceRequired.ClientID%>'), true);
Page_ClientValidate("RequestBookingValidationGroup");

Why does my dropdown keep returning the first item in the dropdown?

I have a dropdown in a vb.net application that is also using radwindow as it's modal. I have the dropdown databinding in the if not ispostback method, yet when I select a value and run it, it still returns the first item. I tried using autopostback set to true but doing that also closes the radwindow. Any other work arounds?
<telerik:RadWindow RenderMode="Lightweight" ID="winComments" runat="server" Title="Comments" RestrictionZoneID="ContentTemplateZone" Modal="true" Width="600" Skin="Outlook"
Height="550" Animation="Fade" Left="600" Top="100" CenterIfModal="true" EnableShadow="true" EnableViewState="false">
<ContentTemplate>
<div class="col-sm-12 col-xs-12">
<br />
<div class="col-sm-4 col-xs-4">
<asp:Label ID="lblCommentVin" runat="server" Font-Bold="true" Visible="true"></asp:Label>
</div>
<div class="col-sm-5 col-xs-5">
Department:
<asp:DropDownList ID="ddlDepartments" runat="server"></asp:DropDownList>
</div>
</div>
<div class="col-xs-12">
<br />
<asp:TextBox ID="txtComment" runat="server" Text="" Height="300px" Width="550px" TextMode="MultiLine"></asp:TextBox>
</div>
<br />
<div class="col-md-offset-4">
<asp:ImageButton ID="btnCancel" runat="server" ImageUrl="images/btnCancel.png" OnClick="btnCancel_Click" CssClass="btn btn-sm pull-right" />
<asp:ImageButton ID="btnSave" runat="server" ImageUrl="images/btnSave.png" OnClick="btnSave_Click" CssClass="btn btn-sm pull-right" />
</div>
</ContentTemplate>
</telerik:RadWindow>
and the code behind:
If Not IsPostBack Then
lblCommentVin.Text = vin
commentDeptList = SQLData.getAssignedCommentDepartments(Session("user"))
_departments = New DepartmentRepository().GetAll()
Session("Departments") = _departments
For Each dept As String In commentDeptList
ddlDepartments.Items.Add(New ListItem(dept, dept))
Next
ddlDepartments.DataBind()
The code stops working where im trying to get the selecteditem
Protected Sub btnSave_Click(sender As Object, e As ImageClickEventArgs)
If txtComment.Text.Length > 1 Then
Dim DepartmentName As String = ddlDepartments.SelectedItem.ToString

Issues with bootstrap popover and asp:button

I would like to replace js windows by bootstrap popover in few pages but I have two issues and I don't find any solutions.
First, if I click on the button to display the popover, required fields are fired directly. Even if I fill in it the message "xx is a required field" stay displayed.
Second, when I try to save my data. Every fields contain an extra character ",". So if I put 10 in the price field in code behind the value of my field is "10,"
Thanks for your help :)
My code:
<asp:Button ID="btnAdd" runat="server" Text="add" CssClass="btn btn-info"data-toggle="popover" data-placement="top" title="add something" ValidationGroup="vgAdd" />
<div id="testBox" class="hide">
<asp:ValidationSummary ID="vsTest" runat="server" ValidationGroup="vgAdd" DisplayMode="BulletList" ShowMessageBox="false" ShowSummary="false" />
<div class="row">
<div class="form-group col-sm-6">
<asp:Label ID="lblPrice" runat="server" Text="price" AssociatedControlID="txtPrice" CssClass="control-label"></asp:Label>
<div class="input-group">
<span class="input-group-addon">$</span>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control" MaxLength="12"></asp:TextBox>
</div>
<asp:CompareValidator ID="cvPrice1" runat="server" Display="None" ValidationGroup="vgAdd" ControlToValidate="txtPrice"
ErrorMessage="price is invalid." ValueToCompare="0" Type="Double" Operator="GreaterThan"></asp:CompareValidator>
<asp:CompareValidator ID="cvPrice" runat="server" Display="None" ValidationGroup="vgAdd" ControlToValidate="txtPrice"
Type="Double" Operator="DataTypeCheck" ErrorMessage="price is invalid."></asp:CompareValidator>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ValidationGroup="vgAdd" ControlToValidate="txtPrice"
ErrorMessage="Default price is a required field." SetFocusOnError="True" Display="Dynamic" />
</div>
<div class="form-group col-sm-6">
<asp:Label ID="lblDesc" runat="server" Text="Description" AssociatedControlID="txtDesc" CssClass="control-label"></asp:Label>
<asp:TextBox ID="txtDesc" runat="server" CssClass="form-control" TextMode="MultiLine" MaxLength="255"></asp:TextBox>
</div>
</div>
<div class="clearfix">
<asp:Button ID="btnSave" runat="server" ValidationGroup="vgAdd" CausesValidation="true"
CssClass="btn btn-primary pull-right"
OnClick="btnSaveTest_Click" Text="Save" />
</div>
</div>
$("[data-toggle=popover]").popover({
html: true,
content: function () {
return $('#testBox').html();
}
});
To fix the first problem you need to remove ValidationGroup="vgAdd" from #btnAdd; you don't want to validate form when this button is clicked.
Regards the second one - there is nothing within your html code what could append comma. You must have something in the back-end code or javascript. I suggest you to debug all the way down from the point when the button #btnSave is clicked - first javascript, then code behind.

asp.net Do not validate Modal form when hidden

I have a modal form (bootstrap), I am using asp.net RequiredFieldValidtors for data entry validation. This validation should only fire when the modal is visible and the user is entering new values into the modal.
The problem I am having is that the validation triggers when the model form is not shown preventing my main page from accepting new data entry from. My modal is only used to add new values and is not part of the normal workflow on my main page.
I have been stuck on this for two days now and have tried many different things and just can't get it figured out.
Any suggestions on how to handle this while keeping my RequiredFieldValidator rules intact?
Thanks
Edit - Adding modal forms code.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<div class="modal fade" id="modNewStakeholder" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Add Stakeholder</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="control-label">First Name:</label>
<asp:TextBox class="form-control focus" ID="tFirstName" runat="server" AutoComplete="off" placeholder="First name is required"></asp:TextBox>
<asp:RequiredFieldValidator ID="rftFirstName"
runat="server" ErrorMessage="Required Field"
ControlToValidate="tFirstName" Display="Dynamic"
ValidationGroup="ValGroupNewStake"></asp:RequiredFieldValidator>
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<asp:TextBox class="form-control" ID="tLastName" runat="server" AutoComplete="off" placeholder="Last name is required"></asp:TextBox>
<asp:RequiredFieldValidator ID="rftLastName"
runat="server" ErrorMessage="Required Field" ControlToValidate="tLastName" Display="Dynamic"
ValidationGroup="ValGroupNewStake"></asp:RequiredFieldValidator>
</div>
<div class="form-group">
<label class="control-label">E-Mail:</label>
<asp:TextBox class="form-control" ID="tEmail" runat="server" AutoComplete="off" placeholder="Email must contain #expeditors.com"></asp:TextBox>
<asp:RequiredFieldValidator ID="rftEmail" runat="server" ControlToValidate="tEmail" Display="Dynamic"
ValidationGroup="ValGroupNewStake"
ErrorMessage="Required Field">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rftEmailAt" runat="server" ControlToValidate="tEmail" Display="Dynamic"
ErrorMessage="Invalid Email, must contain #"
ValidationGroup="ValGroupNewStake"
ValidationExpression="^\w+[\w-\.]*\#\w+((-\w+)|(\w*))\.[a-z]{2,3}$">
</asp:RegularExpressionValidator>
<asp:RegularExpressionValidator ID="rftEmailDomaain" runat="server" ControlToValidate="tEmail" Display="Dynamic"
ErrorMessage="Invalid Email, must be an #abc.com domain"
ValidationGroup="ValGroupNewStake"
ValidationExpression="^.+#[Aa][Bb][Cc][.][Cc][Oo][Mm]$">
</asp:RegularExpressionValidator>
</div>
</div>
<div class="modal-footer">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-success btn-sm" id="cmdOk_AddSholder" runat="server" onserverclick="cmdOk_AddSholder_ServerClick" ValidationGroup="ValGroupNewStake" causesvalidation="false">Ok</button>
<button type="button" class="btn btn-danger btn-sm" id="cmdCancel_AddSholder" runat="server" data-dismiss="modal" onserverclick="cmdCancel_AddSholder_ServerClick">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cmdOk_AddSholder" EventName="serverclick" />
</Triggers>
</asp:UpdatePanel>
I've put together a very simplified example of how my application is doing this. The Modal is just an ascx control and does not have an updatepanel. It's actually just a control becoming visible but we use CSS and JavaScript to make it a modal. The same logic should still apply as I've made this sample from a functioning modal.
Modal.ascx
Validators have ValidationGroup and are disabled. Button is also assigned to ValidationGroup:
<div id="approvalModal" style="display: none;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Enabled="false"
ControlToValidate="TextBox1" ValidationGroup="testValidationgGroup" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="testValidationgGroup" />
</div>
Modal.ascx.vb
Enable the validator in a property:
Partial Class Modal
Inherits System.Web.UI.UserControl
Public WriteOnly Property Enable() As Boolean
Set(value As Boolean)
RequiredFieldValidator1.Enabled = value
End Set
End Property
End Class
PageWithModal.aspx (note: uses jQuery)
<script>
function setupTestModal() {
var modal = $('#approvalModal');
if (modal.css('display') == 'none') {
modal.show();
}
}
</script>
<asp:Button ID="ShowModal" runat="server" Text="Show Modal" OnClick="ShowModal_Click" />
<uc1:Modal runat="server" ID="testModal" />
PageWithModal.aspx.vb
Notice that when you click the ShowModal button, the validation does NOT fire. However, when the modal is visible, the Validator has been enabled.
Protected Sub ShowModal_Click(sender As Object, e As EventArgs)
testModal.Enable = True
Dim script = String.Concat("setupTestModal();")
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType(), "Popup", script, True)
End Sub

Populate bootstrap modal from gridview edit link button

I have a gridview containing membership providers roles.
With Link Button For editing and Link button for deleting.
I want to populate a modal with a text box inside it to save the role name as shown.
I succeeded in populating the modal and binding the grid and all of that, but, how can I bind the txtRoleName in the modal with the role name of the row? Preferably without any postback if possible, or with postback if not.
Here is the code for the grid:
<asp:GridView ID="grdRoles"
CssClass="table table-bordered responsive"
runat="server"
GridLines="None"
CellSpacing="-1"
AutoGenerateColumns="False"
OnPageIndexChanging="grdRoles_PageIndexChanging"
OnRowDataBound="grdRoles_RowDataBound"
ShowFooter="True" ShowHeaderWhenEmpty="True" EmptyDataText="Empty !">
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<asp:Label ID="lblRank" runat="server" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roles">
<ItemTemplate>
<asp:Label ID="lblRoleName" runat="server" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" data-toggle="modal" href="#EditModal" runat="server" CssClass="btn icon-edit" />
<asp:LinkButton ID="btnRemove" runat="server" CssClass="btn btn-danger remove" Text="<i class=icon-remove></i>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And this is the code for the modal:
<div id="EditModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="Edit"
aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="helpModalLabel"><i class="icon-external-link"></i> Edit Role</h3>
</div>
<div class="modal-body">
<div class="control-group">
<div class="controls">
<div class="input-prepend">
<span class="add-on">Role Name</span>
<asp:TextBox ID="txtRoleName" Text='<%# Bind("RoleId") %>' runat="server"></asp:TextBox>
</div>
</div>
<div class="form-actions">
<asp:Button ID="btnSave" type="submit" class="btn btn-primary" runat="server" Text="Save" />
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
I am using data property to send data to the modal:
<a id="edit" href="#dlgName" data-toggle="modal" role="button"
data-id="<%# DataBinder.Eval (Container.DataItem, "Id") %>"
data-IsPrimary ="<%# DataBinder.Eval(Container.DataItem, "IsPrimary") %>" >Edit</a>
And, retrieve the data using jQuery:
var Id = $('#edit').data('Id');
var isprimary = $('#edit').data('IsPrimary');

Resources