Dropdownlist and field validation is causing a riot - asp.net

For some reason, I can't get the validator to raise a flag when I do things wrong.
<asp:DropDownList ID="ddlTypeList" runat="server" DataSourceID="ods_TypeOptions" DataTextField="name" DataValueField="id" SelectedValue='<%# Bind("Type") %>' AppendDataBoundItems="true">
<asp:ListItem Text="-" Value="-1" Selected="True"></asp:ListItem>
</asp:DropDownList>
The drop down list has nice values, incl the initial dummy.
Neither
<asp:RequiredFieldValidator ID="rfw" runat="server" ControlToValidate="ddlTypeList"
InitialValue="-1" ToolTip="Required">*</asp:RequiredFieldValidator>
Nor
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="ddlTypeList" ValueToCompare="-1" Operator="NotEqual" ToolTip="Required">*</asp:CompareValidator>
Raises any flags to say "hey - u messed up, go fix it". For all the google, searching, reviews, swinging big hammers, I have yet to spot what I am doing wrong.
I just want one solution to fix them all.
Oh yes, I also had a ValidationGroup="myGroup" between the DDL, RFV/CV and the button. No luck.

Your code is correct. You must have some element of code or markup that is obstructing the functionality of the validator. Is it possibly that the "-" item has its value changed from "-1" to something else?
Verify that your button that submits the form has CausesValidation=True.Also, make sure that the parent of the validators is not set to Visible=False or the children will not render on the page.
Verify that the RequiredFieldValidator and CompareValidator are rendering in the markup by searching for "_cv" or possibly "cv" in the outputted markup. If it is not there, then one of the parent elements is not being rendered or the validators are being deleted.

Related

.net ascx control not retaining value on postback (mojoPortal)

I'm making a custom module for mojoPortal CMS which needs to allow the client to add an affiliate into the database. As far as I can tell, this requires creating a .ascx file and then installing that using the administration toolbar in the Web interface to get it to a point where I can put it into a page, as http://www.mojoportal.com/hello-world-developer-quick-start.aspx.
The form is simple enough, but the values in the text boxes just stay empty when I submit, though the file upload works fine. The code:
<asp:Label ID="Label1" runat="server" Text="Company Name" AssociatedControlID="CompanyName">
</asp:Label>
<asp:TextBox ID="CompanyName" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Company Description" AssociatedControlID="CompanyDescription"></asp:Label>
<asp:TextBox ID="CompanyDescription" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="Company Logo" AssociatedControlID="CompanyLogo"></asp:Label>
<asp:FileUpload ID="CompanyLogo" runat="server" />
<asp:Button ID="SubmitButton" runat="server" Text="Add Affiliate" />
EnableViewState for the page and the controls is enabled
The text box is not set to ReadOnly, and there is no funky JavaScript dynamically modifying elements (at least, I didn't set any).
I can work around this by using HTML elements, and get the values using Request.Form. The information is actually there, I can see it in the Request.Form, but I would have to get that by something like Request.Form[CompanyName.ClientId.Replace("_","$")] or Request.Form[6] which both seem very messy and IIRC aren't really the way things are supposed to roll in .NET. Besides, having worked until 3 last night, I really want to know what the answer is now!
Any thoughts anyone?
What I had done was not created a click event for the button, relying on the fact that it was posting to the server (like I would in PHP). Oops! When I added a click event, then the text boxes retained their value when I was within that method.

Accordion's First Pane Flashes On Partial Postback

I'm using an ASP.NET Accordion control with lots of panes for a data entry form. Within several of the panes are some UpdatePanels, so that some controls within those panels can be enabled or disabled to prevent users from entering values into fields which are precluded by values they've entered elsewhere.
It all works fine, but for some reason, on about half of the occasions where an UpdatePanel postback is triggered (by a specified AsyncPostBack Trigger), the first pane of the Accordion momentarily expands and collapses. This gives that horrible 'flashing' experience you get when a page does a full postback, which is exactly what I'm trying to avoid by using UpdatePanels.
The problem doesn't seem to relate to the contents of the first pane - I tried completely deleting the first pane, so that the second pane became the first, and the same thing happens.
Anybody got any ideas why this is happening and how to fix it?
UPDATED WITH CODE
This is an example of one of the panels. Don't be too offended by the use of a table - it's an actual table, I'm not just using it for layout purposes!
<tr class="grouprow">
<td>Transportation</td>
<td><asp:RadioButtonList ID="rblTransportation" runat="server" RepeatDirection="Horizontal" SelectedValue='<%# Bind("AdmissionTransportation")%>' AutoPostBack="true"
OnSelectedIndexChanged="rblTransportation_SelectedIndexChanged" >
<asp:ListItem Text="Unknown" Value="" />
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:RadioButtonList></td><td></td>
</tr>
<tr class="grouprow">
<td>Transportation Duration</td>
<td><asp:UpdatePanel ID="updTransportationHours" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rblTransportation" EventName="selectedindexchanged" />
</Triggers>
<ContentTemplate>
<asp:TextBox ID="txtTransportationHours" runat="server" Text='<%# Bind("AdmissionTransportationHours")%>' CssClass="tinytextbox" />
<label class="unit">Hours</label>
<asp:RegularExpressionValidator ID="revTransportationHours" runat="server" ControlToValidate="txtTransportationHours" ValidationExpression="\d{1,3}(\.\d{1,2})?"
ValidationGroup="Past30Days" ErrorMessage="Invalid format for Transporation Duration. Please enter in format 'xxx.xx', e.g. '3.25'" Display="Dynamic"
CssClass="error" >*</asp:RegularExpressionValidator>
<asp:RangeValidator ID="rvTransportationDuration" runat="server" ControlToValidate="txtTransportationHours" CssClass="error" ValidationGroup="Past30Days" type="Double"
ErrorMessage="The Transportation Duration cannot be more than 100" MinimumValue="0" MaximumValue="100" >*</asp:RangeValidator>
</ContentTemplate>
</asp:UpdatePanel></td><td></td>
</tr>
I believe you need your rblTransportation RadioButtonList wrapped in an UpdatePanel as well.
Since that control isn't in an UpdatePanel, it causes a full postback.
The answer is gloriously simple, though I'm too tired to figure out why it works just now. I simply need to set ClientIDMode = AutoID on the RadioButtonLists and CheckBoxLists and they now trigger an asynchronous postback rather than a full one. They don't need to be within their own UpdatePanels either.
I got the answer from this SO question.
Can you try <asp:blablacontrol style="Display:none;"> </asp:control>
modalpanels has same problem and this codes solved my problem

RequiredFieldValidator have to click twice

I have run into the same problem as described here.
Only the question is marked as answered with only an explanation as to why you may have to click twice when using a RequiredFieldValidator on input fields - once as the blur of a textbox(for example) will correct the validation and then again to actually post the form.
I don't want to have to click a button twice! Does anyone know a solution or workaround to this?
You could add EnableClientScript=false to the validator.
That prevents the client-side validation, so you will always get a postback (which may not exactly be what you want, though). The validation will still be done, just server-side.
Be sure to wrap the button-click logic in a if (Page.IsValid) { ... }, to check the status of the validators.
Apologies for not posting code previously I assumed this to be a standard problem with the RequiredFieldValidator, but have since realised my particular problem was coming from a CompareValidator, used to ensure entered passwords matched.
The CompareValidator was causing the issue that I described, causing me to have to click away from the field to blur and validate, before being able to click on the post button.
I'm not sure why but changing the Display of the CompareValidator from Dynamic to Static has cleared the problem up.
If the validator is Display="Dynamic", and the appearance of the error message causes the submit button to move, then the MouseUp event is not received by the submit button. In this case, the validation fires and clears the error message, but the submit button does not fire. To solve the problem, either set the the validators to be Display="Static", or rearrange the form so that the submit button does not move when error messages appear.
Here's a way to reserve about one, vertical line of space for a dynamic validation message:
<div style="height:1.5em;overflow:visible;">
<asp:RequiredFieldValidator ID="R1" runat="server"
ErrorMessage="Name is required" ControlToValidate="TextBoxName"
Display="Dynamic"></asp:RequiredFieldValidator>
</div>
I did not find it necessary to set EnableClientScript="false", although that did help for a CustomValidator that had no client-side validation function implemented.
Posting your code is always a good idea, That way we could run your code in a test environment and modify it to ensure it works before posting our answer.
I would suggest adding
causesValidation="true"
to your button to see if that works.
I have a better idea.
Add Text="" to textbox Control.
Add InitialValue="" to Validator Control.
What it will do, when it will be posting, it will find the value of the text box is still the initail value and it will throw an error and the form will not be posted.
Try this:
<asp:RequiredFieldValidator ID="reqFieldCloseComment" ControlToValidate="tbCloseComment" ValidationGroup="ChangeStatus" ErrorMessage="Please enter a reason" Display="Dynamic" runat="server" InitialValue=""></asp:RequiredFieldValidator>
<asp:TextBox ID="tbCloseComment" runat="server" CausesValidation="true" TextMode="MultiLine" Height="107px" Width="400px" Text=""></asp:TextBox>
<asp:Button ID="btnCloseRequestFinal" Text="Finish" CssClass="CloseReqButton" runat="server" ValidationGroup="ChangeStatus" />
Here is code that is working fine for me and helping to get rid of double click.
<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"
Enabled="true" MaxLength="20" onfocus="SetActiveControl(this);" Text=""
CausesValidation="true" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1" Display="Static" ErrorMessage="Ha!" SetFocusOnError="True" EnableClientScript="true" ForeColor="" InitialValue="" />
$(function() {
$("input.btn").on("click",function(){
if(Page_BlockSubmit == true) {Page_BlockSubmit = false};
})
});
Page_BlockSubmit is a JS variable defined by the js generated from code behind when you define the validator . I haven't went deeper to know why MS need this variable, but the scenario is:
the first click will make Page_BlockSubmit become false.
the second click will check the value of Page_BlockSubmit and return true.
if you implemented the code I posted, every time you click the button, the variable will be set as false which will trigger the submit at every click.
And, you can use google chrome to trace the value of Page_BlockSubmit.

Custom validation not working with delete buttons?

In a ListView, I have a CustomValidator set up to validate a field whenever a button with CommandName="Delete" is clicked.
<ItemTemplate>
<asp:TextBox ID="NameTextBox" Text=<%# Eval("Name") %> runat="server" />
<asp:Button ID="DeleteButton" Text="Delete" CommandName="Delete" ValidationGroup="Delete" runat="server" />
<asp:CustomValidator ValidationGroup="Delete" SetFocusOnError="true" Display="Dynamic" OnServerValidate="CustomValidator_ServerValidate" runat="server">You can't delete this.</asp:CustomValidator>
</ItemTemplate>
However, the error message is never displayed and the processing continues. What's strange is that the custom validation method is called, finds the field, and properly sets up e.IsValid to false. It does not matter whether I check Page.IsValid or not, because the error message is not displayed anyway.
It works if I remove the CommandName="Delete" from the button.
With Google I found the following solution, which seems to indicate someone has had a similar issue:
http://devio.wordpress.com/2007/12/11/formview-delete-button-and-customvalidators/
But I want to make sure that this solution is the way to go. I mean, is custom validation really not supposed to work with a delete button in a databound control, seriously?
I've alrealy heard about a problem like that, he solved it by doing it entirely differently. Like, instead of the customValidator, he puts a Label set EnableViewState="False" and Visible="False" and he check on the delete event the conditions and put the response back into the label. Maybe it can't works for you too?
But, if you realy ask "Why?????", I know he didn't find the exact reason ...

RequiredFieldValidator not working

With the following simple mark-up, I get very strange behaviour in FF and IE8. If I give the textbox focus, and tab out, nothing happens. If I give a user name value, and erase it immediately, nothing happens. However, only when I supply a user name, tab away, the erase it and tab away again, do I finally get a red star "required" mark. The summary doesn't show at all.
This is the markup I was trying with. Looks like my issue was with EnableClientScript and ValidationGroup:
<asp:Label ID="userNameLabel" runat="server"
AssociatedControlID="userNameText">
User Name:
</asp:Label>
<asp:TextBox ID="userNameText" runat="server"
Width="200px">
</asp:TextBox>
<asp:RequiredFieldValidator ID="userNameRequired" runat="server"
ControlToValidate="userNameText"
Display="Dynamic"
EnableClientScript="true"
ValidationGroup="userValidation"
ErrorMessage="User Name is always required.">
*
</asp:RequiredFieldValidator>
Are you sure EnableClientScript="true" is even needed? I think it defaults to that.

Resources