Validation Group in Asp.Net MultiView - c#

I have multiView and Validation group in my code. According to my code when user press button all the data in views needs to be saved.
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="viewGegevens" runat="server">
<asp:TextBox ID="txtCompanyname" MaxLength="100" runat="server" CssClass=""></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ToolTip="Bedrijfsnaam vereist!"
Display="Dynamic" ErrorMessage="*" ValidationGroup="Save" ControlToValidate="txtCompanyname"
CssClass="required-asterics"></asp:RequiredFieldValidator>
<div>
<asp:LinkButton ID="btnSave1" Text="Opslaan" runat="server" CssClass="btn-ctrl right" OnClick="txtSave1_Click" ValidationGroup="Save">Save
</asp:LinkButton>
<asp:LinkButton ID="btnCancel1" Text="Annuleren" runat="server" CssClass="btn-ctrl right" OnClick="txtCancel1_Click"> Cancel
</asp:LinkButton>
</div>
</asp:View>
<asp:View ID="viewGegevens2" runat="server">
<asp:TextBox ID="txtBillingPostalCode" runat="server" CssClass="" MaxLength="100"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ToolTip="Postcode vereist!"
ErrorMessage="*" ValidationGroup="Save" ControlToValidate="txtBillingPostalCode"
Display="Dynamic" CssClass="required-asterics"></asp:RequiredFieldValidator>
<div>
<asp:LinkButton ID="btnSave2" Text="Opslaan" runat="server" CssClass="btn-ctrl right" OnClick="txtSave2_Click" ValidationGroup="Save">Save
</asp:LinkButton>
<asp:LinkButton ID="txtCancel2" Text="Annuleren" runat="server" CssClass="btn-ctrl right" OnClick="txtCancel2_Click"> Cancel
</asp:LinkButton>
</div>
</asp:View>
</asp:MultiView>
My problem is i need to fire required field validation in both tabs either user press btnSave1 or btnSave2.
But now if i press btnSave1 it only fires validations in 1st tab only. How can i solve this?

Found a workaround for this that works in my case. I made the different views validate when the tabs are clicked in the code behind preventing the user from leaving the view without validating.
protected void Tab3_Click(object sender, EventArgs e)
{
Page.Validate("YourValidationGroup");
if (Page.IsValid)
{
Tab1.CssClass = "Initial";
Tab2.CssClass = "Initial";
Tab3.CssClass = "Clicked";
MainView.ActiveViewIndex = 2;
}
}
I know this in an old thread but figured I'd throw it out there for future people experiencing a similar issue.

The answer is no, you can't do it like this out of the box.
ASP.NET Multiview is designed to display and validate one view at a time. So only the active view's html is delivered to the client's browser.
There is a workaround but may give you problems if you are using MultiView's ActiveViewChanged event.
Another option would be to refactor your page and use two divs, one for each step, making one or the other visible when changing from first to second step, and validate entire page once in the last step. This will require you to do more work with javascript.

Try this:
SelectView(0);
Validate();
if (IsValid)
{
SelectView(1);
Validate();
if (IsValid)
{
SelectView(2);
Validate();
if (IsValid)
{
SelectView(3);
Validate();
if (IsValid)
{
UpdateHeader();
Response.Redirect("FinConfLanding.aspx");
}
}
}
}

Related

Postback via update panel resets TabIndex?

This is the only related post I've found so far on SO, not my exact issue, but close.
If I give focus to the first textbox on my page and then press TAB repeatedly until I reach the last control on my page the tab order works flawlessly, every control is given focus in the correct order.
BUT...
If I am actually filling out the form and I select a value in ANY dropdownlist, when I press TAB after selecting the value focus is given to the first textbox on my page rather than the next control after said dropdownlist.
I created a control that includes a label, a dropdownlist and an imagebutton because this list is used multiple times throughout my application. The control looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="OrganizationList.ascx.cs" Inherits="MyApp.Web.Controls.OrganizationList" %>
<%# Register src="UpdateProgress.ascx" tagname="UpdateProgress" tagprefix="uc1" %>
<%# Register src="Address.ascx" tagname="Address" tagprefix="uc2" %>
<asp:UpdatePanel ID="OrganizationUpdatePanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<div style="margin: 0px;">
<div class="label"><asp:Label ID="Prompt" runat="server"></asp:Label>:</div>
<div class="field"><asp:DropDownList ID="Organizations" runat="server" Width="205" AutoPostBack="True" DataTextField="Name" DataValueField="Id"></asp:DropDownList> <asp:ImageButton id="AddOrganization" runat="server" ImageAlign="AbsMiddle" ToolTip="Add a new organization" onclick="AddOrganization_Click" /></div>
</div>
<asp:HiddenField ID="DummyButton" runat="server" />
<ajax:ModalPopupExtender ID="AddOrganizationModalPopupExtender" runat="server" BackgroundCssClass="modalBackground" CancelControlID="Cancel" DropShadow="true" PopupControlID="NewOrganization" RepositionMode="RepositionOnWindowResizeAndScroll" TargetControlID="DummyButton"></ajax:ModalPopupExtender>
<asp:Panel ID="NewOrganization" runat="server" CssClass="modalPopUp" Width="500">
<asp:Panel ID="OrganizationModalContent" runat="server" CssClass="modalContent" GroupingText="Add Organization" style="text-align: left; vertical-align: top;" Width="490">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr><td colspan="2"><asp:ValidationSummary ID="OrganizationValidationSummary" runat="server" CssClass="ValidationSummary" ValidationGroup="NewOrg" /></td></tr>
<tr><td class="label"><asp:RequiredFieldValidator ID="NameRequired" runat="server" ControlToValidate="Name" Display="Dynamic" ErrorMessage="Please provide the organization's name." SetFocusOnError="true" ValidationGroup="NewOrg">*</asp:RequiredFieldValidator>Organization Name:</td>
<td><asp:TextBox ID="Name" runat="server" MaxLength="100" Width="200"></asp:TextBox></td></tr>
<tr><td class="label"><asp:RequiredFieldValidator ID="PhoneRequired" runat="server" ControlToValidate="Phone" Display="Dynamic" ErrorMessage="Please provide the organization's phone number." SetFocusOnError="true" ValidationGroup="NewOrg">*</asp:RequiredFieldValidator>Phone:</td>
<td><ajax:MaskedEditExtender ID="PhoneMaskedEditExtender" runat="server" ClearTextOnInvalid="true" InputDirection="LeftToRight" Mask="(999)999-9999" MaskType="Number" MessageValidatorTip="true" PromptCharacter="_" TargetControlID="Phone"></ajax:MaskedEditExtender>
<asp:TextBox ID="Phone" runat="server" MaxLength="10" Width="200"></asp:TextBox></td></tr>
<tr><td class="label">Fax:<br />(optional)</td>
<td><ajax:MaskedEditExtender ID="FaxMaskedEditExtender" runat="server" ClearTextOnInvalid="true" InputDirection="LeftToRight" Mask="(999)999-9999" MaskType="Number" MessageValidatorTip="true" PromptCharacter="_" TargetControlID="Fax"></ajax:MaskedEditExtender>
<asp:TextBox ID="Fax" runat="server" MaxLength="10" Width="200"></asp:TextBox></td></tr>
<tr><td colspan="2"><uc2:Address ID="Address" runat="server" /></td></tr>
<tr><td colspan="2" style="text-align: right;"><asp:HiddenField ID="TypeOfList" runat="server" /><asp:Button ID="Submit" runat="server" CausesValidation="true" Text="Submit" onclick="Submit_Click" ValidationGroup="NewOrg" /><asp:Button ID="Cancel" runat="server" Text="Cancel" /></td></tr>
</table>
</asp:Panel>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<uc1:UpdateProgress ID="OrganizationUpdateProgress" runat="server" AssociatedUpdatePanelId="OrganizationUpdatePanel" />
Here's the TabIndex property on my control:
public short TabIndex
{
get { return Organizations.TabIndex; }
set { Organizations.TabIndex = value; AddOrganization.TabIndex = (short)(value + 1); }
}
Here's one of the references to the control on the parent page:
<uc3:OrganizationList ID="ReportedBy" runat="server" FieldLabel="Reported By" ListType="ReportedBy" TabIndex="105" />
Not sure what else you might want/need to see.
Browsers: IE8, IE9, IE10, FF 29.0.1
We've had some issues with IE versions above 9, so I added a HTTP Response Header to emulate IE9
My users claim that they primarily TAB to navigate in my app, so this is actually a higher priority bug than I expected. I don't know why the TabIndex is ignored once a value is selected.
Any ideas would be greatly appreciated.
UPDATE:
I do have 1 dropdownlist that is just an out-of-the-box dropdownlist, not a user control. That one works correctly. I can select a value in that list and then press TAB and the focus moves to the next control. So, can anyone help me figure out what is "wrong" with my user control that is causing this bug?
These two posts helped me figure out what I needed to do:
A postback via update panel resets TabIndex?
Accessing ToolKitScriptManager/ScriptManager from custom control
I added a SelectedIndexChanged event handler to my DropDownList in my control and set the focus back to the DropDownList. Here's the code:
protected void Organizations_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ScriptManager scriptMgr = ScriptManager.GetCurrent(Page);
scriptMgr.SetFocus(ddl);
}
Here's the control on the .aspx page:
<asp:DropDownList ID="Organizations" runat="server" Width="205" OnSelectedIndexChanged="Organizations_SelectedIndexChanged" AutoPostBack="True" DataTextField="Name" DataValueField="Id"></asp:DropDownList>
2014.05.22 UPDATE:
In my custom control I have an image button (+) named AddOrganization. In testing the fix yesterday we discovered that if a user clicked the '+' to add a new organization...after they saved the organization...the new value would get auto-selected (as expected) but the tabbing would get reset again. So I had to modify my button click event handler:
protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Do stuff...save organization
// update the list
BindOrganizationList();
// select the new value
Organizations.SelectedIndex = Organizations.Items.IndexOf(Organizations.Items.FindByText(OrganizationName.Text.ToUpper().Trim()));
// reset the form
ResetOrganizationForm();
OrganizationUpdatePanel.Update();
// set focus back to the dropdownlist
ScriptManager scriptMgr = ScriptManager.GetCurrent(Page);
scriptMgr.SetFocus(Organizations);
}
else
{
// Display friendly validation messages to user
}
}

Enable/Disable Required field validator from cs page?

I have two TextBox and two Buttons in my page.
One is hidden and the other one is displayed.
When I click the Button1, it will save data of the two TextBox and will validate each TextBox by the RequiredFieldValidator.
Then when I click Button2, it will just hide itself (Button2) and will show the hidden TextBox.
Both TextBox has RequiredFieldValidator validating against Button1's Event click.
Now my issue is when I simply enter text to the 1st TextBox and click save, the button click is validating the required field for hidden field. I just want to validate the 2 textbox when it is showing.
How can I avoid this?
Well you can simple use the Enabled="false" property of RequiredFieldValidator.
Your markup would look something like this based on your Question.
<asp:TextBox runat="server" ID="tb1"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv1" ControlToValidate="tb1" ErrorMessage="*" ValidationGroup="gvSave">
</asp:RequiredFieldValidator>
<asp:TextBox runat="server" ID="tb2" Visible="false"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv2" ControlToValidate="tb2" ErrorMessage="*" Enabled="false" ValidationGroup="gvSave">
</asp:RequiredFieldValidator>
<asp:Button runat="server" ID="btn1" Text="Save" onclick="btn1_Click" ValidationGroup="gvSave"/>
<asp:Button runat="server" ID="btn2" Text="Show" onclick="btn2_Click" />
And your codebehind like this:
protected void btn2_Click(object sender, EventArgs e)
{
tb2.Visible = true;
rfv2.Enabled = true; // Enables the second requiredfieldvalidator
}
protected void btn1_Click(object sender, EventArgs e)
{
// your Saving code here
}
use the ValidationGroup="group" property to button and assign validation group to text on which you want to validate.
Hope it will help
You can specify CausesValidation="false" for the secondary button, this is less verbose and potentially confusing when validation groups are A) excessive for a single field and B) you have to maintain validation groups when adding further controls (do we put it on the button, the validator, the field and the validation summary? It's not a lot the remember the standard, but less practical when editing.
This is Aspx :
<td align="right">
Cut Type :
</td>
<td class="required">
<telerik:RadComboBox ID="cmbCutType" runat="server" MaxHeight="200px" Width="200px"
Filter="Contains" EnableLoadOnDemand="true" EmptyMessage="Select Cut Type" OnSelectedIndexChanged="cmbCutType_SelectedIndexChanged"
AutoPostBack="true">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" ID="rfvCutType" Display="None" ControlToValidate="cmbCutType" InitialValue=""
ValidationGroup="Save" ErrorMessage="Cut Type is Mandatory"
ForeColor="Red"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceCutType" TargetControlID="rfvCutType"
runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
</td>
This is code behind :
protected void btn2_Click(object sender, EventArgs e)
{
rfvCutType.IsValid = false;
}
try this.......
If you wish you use backend validation then check this out, it worked for me.
Requiredfieldvalidator.Enabled = False
Requiredfieldvalidator is an ID.
The project I am working has all the fields visible but based on certain conditions, validation has to be disabled.

asp.net Disable Button after Click while maintaining CausesValidation and an OnClick-Method

.aspx
<asp:TextBox ID="txtInvite" Width="170px" Height="20px" runat="server"
Font-Size="Small" ></asp:TextBox>
<AjaxToolkit:TextBoxWatermarkExtender ID="tbexInvite"
runat="server" SkinID="skinTextBoxWatermarkExtender"
TargetControlID="txtInvite" WatermarkText="Email"></AjaxToolkit:TextBoxWatermarkExtender>
<asp:RequiredFieldValidator ID="rfvInvite" runat="server"
Display="None" ValidationGroup="Inivitation" SetFocusOnError="true"
ControlToValidate="txtInvite" ErrorMessage="Enter Email."></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regExpInvite" runat="server"
Display="None" ValidationGroup="Inivitation" SetFocusOnError="true"
ValidationExpression="\s*\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*\s*"
ControlToValidate="txtInvite" ErrorMessage="Invalid Email Format."></asp:RegularExpressionValidator>
<div class="ButtonLogin" style="margin-top:-27px;margin-right:143px;_margin-right:105px;">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<asp:Button ID="btnInvite" runat="server" CssClass="cssLoginButton blue" Text="Invite" ToolTip="Invite" ValidationGroup="Inivitation" CausesValidation="true" onclick="btnInvite_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="0">
<ProgressTemplate>
<asp:Image ID="Image1" ImageUrl="~/App_Themes/Lifetrons/images/progressbar.gif" AlternateText="Processing" runat="server" />
</ProgressTemplate>
</asp:UpdateProgress>
Page_load Code
.CS
this.btnInvite.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(this.btnInvite, "").ToString());
I want to disable button after clicking on it with maintaining validation and Onlick method. I refer to this question my problem is same like this question but I haven't solve my problem. How can I solve?
There is no need to mess around with your code-behind Page_Load event. In your button control, just add the following snippet:
OnClientClick="if(Page_ClientValidate('Inivitation')){this.disabled=true;}"
So that your button looks like
<asp:Button ID="btnInvite" runat="server" CssClass="cssLoginButton blue" Text="Invite"
ToolTip="Invite" ValidationGroup="Inivitation" CausesValidation="true"
onclick="btnInvite_Click" OnClientClick="if(Page_ClientValidate('Inivitation')){this.disabled=true;}" />
You should be able to disable the button using the Button_Click method. Make your first line something like this:
Button.Enabled = False;
There is a problem with this method though. If the page loads too quickly or the code freezes it will not disable the button properly. Just remember to re-enable the button at the end of the method if the validation fails or times out.
Another method you may try is to hide it using CSS. I am a big fan of this because it always works and it is very simple. You need a technology like jQuery where you can add classes on the fly. You can use the AddClass and RemoveClass API in jQuery to add/remove CSS classes at runtime. Take a look here. http://jqueryui.com/addClass/
you can use Like this
<asp:Button ID="btnInvite" runat="server" CssClass="cssLoginButton blue" Text="Invite" ToolTip="Invite" ValidationGroup="Inivitation" CausesValidation="true" UseSubmitBehavior = False"onclick="btnInvite_Click" />

asp.net wizard control, set step name unvisible

I don't want to show stepname. "Next" and "finish button" is enough for me. How to unvisible these?!
Second question's; after FinishButton's click, I want to redirect first step automatically. How to do?
<asp:Wizard runat="server" ID="MyWizard" OnNextButtonClick="MyWizard_NextButtonClick"
Width="440px" Height="200px" OnFinishButtonClick="MyWizard_FinishButtonClick">
<WizardSteps>
<asp:WizardStep ID="Wizardstep1" runat="server" StepType="auto">
</asp:WizardStep>
<asp:WizardStep ID="Wizardstep2" runat="server" StepType="auto">
</asp:WizardStep>
You can create your custom LayoutTemplate within Wizard control to hide step names. For example:
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="headerPlaceHolder" runat="server" />
</div>
<div>
<asp:PlaceHolder ID="wizardStepPlaceholder" runat="server" />
</div>
<div>
<asp:PlaceHolder ID="navigationPlaceholder" runat="server" />
</div>
</LayoutTemplate>
Remeber that placeholders' id names matter. Placeholer responsible for displaying list of steps that you circled has id sideBarPlaceHolder (and you should not have any placeholder with this id inside LayoutTemlpate)
Second question:
You can have custom navigation template, for example:
<FinishNavigationTemplate>
<asp:Button ID="PreviousButton" runat="server" Text="Previous step" CausesValidation="false" CommandName="MovePrevious" />
<asp:Button ID="FinishButton" runat="server" Text="Finish" CausesValidation="true" CommandName="MoveComplete" OnCLick="FinishButton_Click" />
</FinishNavigationTemplate>
Note that these buttons have fixed CommandName (Wizard control expects this). You can try to use finish button's OnClick event to jump to the first step:
protected void FinishButton_Click(object sender, EventArgs e)
{
yourWizard.ActiveStepIndex = 0;
}

multiple submit buttons won't postback on aspx - only last button

On my aspx page I have two fieldsets, each wrapped with an <asp:Panel DefaultButton="..."> that have their own <input type="submit"> buttons. Here's an abbreviated version...
<div id="content">...</div>
<asp:Panel runat="server" id="formPanel1" DefaultButton="form1SubmitButton">
<fieldset>
<asp:TextBox runat="server" id="textbox1"/>
<asp:TextBox runat="server" id="textbox2"/>
<asp:Button runat="server" id="form1SubmitButton" OnClick="form1SubmitButton_OnClick"/>
</fieldset>
</asp:Panel>
<asp:Panel runat="server" id="formPanel2" DefaultButton="form2SubmitButton">
<fieldset>
<asp:TextBox runat="server" id="textbox3"/>
<asp:TextBox runat="server" id="textbox4"/>
<asp:Button runat="server" id="form2SubmitButton" OnClick="form2SubmitButton_OnClick"/>
</fieldset>
</asp:Panel>
Only the last submit button form2SubmitButton will postback, the other button does nothing when clicked. I have simplified the code above but I should mention that each form, Panel included, is kept in a separate user control that is registered on the aspx.
UPDATE: After some more research I've figured out that the submits are not working because of validators on the another fieldset on the master page. That fieldset is for signing into the site, so it is needed. Thoughts?
As PCasagrande mentioned, make sure your validation groups match the default button and all validators. Specially for your logging part.
Example:
<asp:Panel ID="pnlUpdateInfo" runat="server" DefaultButton="btnUpdateInfo">
<ASP:TEXTBOX id="txtZip" runat="server"></ASP:TEXTBOX>
<asp:RequiredFieldValidator id="reqvalZipSignUp" runat="server"
ControlToValidate="txtZip" ValidationGroup="btnUpdateInfo" />
<asp:Button ID="btnUpdateInfo" runat="server" ValidationGroup="btnUpdateInfo" />
</asp:Panel>
Turns out it has to do with HTML5 constraint validation. I figured this out because in chrome, from the console, I was getting the error An invalid form control with name='...' is not focusable. This led me to this post. I added the html5 attribute formnovalidate="formnovalidate" to the submit buttons and everything works just fine (*tested in chrome v20.0.1132.57, firefox v14.0.1, IE9 v9.0.8112).
So to recap, here's the answer...
<asp:Button runat="server" id="submit1" OnClick="submit1_OnClick" text="Submit" formnovalidate="formnovalidate"/>

Categories

Resources