Setting a server control property from the content page - asp.net

I need to validate a textbox to ensure the submit date is older than Today. I wanted to use a CompareValidator to do that, but unfortunately the following code doesn't work:
<asp:CompareValidator ID="cvtbDateExpiration" ControlToValidate="tbDateExpiration"
Operator="GreaterThan" Type="Date" ValueToCompare="<%= DateTime.Today %>"
ErrorMessage="Card has expired" runat="server" />
The compiler tells me that ValueToCompare="<%= DateTime.Today %>" is wrong: "This is not scriptlet. Will be output as plain text."
Is there a simple way to achieve this (without setting it using the Code Behind)?
Thanks!

It's generally set as follows:
ValueToCompare='<%# DateTime.Today.ToString("MM/dd/yyyy") %>'
... and you have to call DataBind() on the control (directly or indirectly).

Related

ASP.NET server tags rendered in client HTML, not values?

Maybe I've forgotten how to use these, but I am going crazy trying to inject a server-side value into an HTML output. There are reasons why I am doing this inline, and not server-side, so please don't suggest that as a solution.
This code on the server side:
<asp:Label ID="Label1" runat="server" Text='<%= DateTime.Now.ToString() %>' />;
Renders as this in the client HTML sent to the browser:
<span id="Label1"> <%= DateTime.Now.ToString()></span>;
And it displays as big fat empty space, and nothing output to the interface.
If I change the ASP source to using the "#" character to define as data-binding syntax, then the rendered output to browser becomes:
<span id="Label1"></span>
EDIT:
Setting Label text was just a simplified object for the sake of asking the question. In real life, I am setting the CssClass attribute, which does not allow me to use the "wrapping" workaround some have suggested. I wanted to set a public property and have all the controls update from it dynamically on page load.
Ideally, since I already have all the controls laid out on the aspx page. Just looking to add an attribute. I wanted to have:
<asp:textbox ID='MyTxtBox1' CssClass='<% strVal1 %>' />
<asp:textbox ID='MyTxtBox2' CssClass='<% strVal1 %>' />
<asp:textbox ID='MyTxtBox3' CssClass='<% strOtherVal %>' />
<asp:textbox ID='MyTxtBox4' CssClass='<% strVal1 %>' />
Now what it looks like I need to do is repeat all my (250+) controls on the codebehind in a block of code that looks like:
MyTxtBox1.CssClass=strVal1
MyTxtBox2.CssClass=strVal1
MyTxtBox4.CssClass=strVal1
MyTxtBox3.CssClass=strOtherVal
I believe that may not work on a compiled Web Application as it's not interpreted at run-time like a C# "Web Site". However, I was able to get it to work wrapping the label around the value:
<asp:Label runat="server"><%= DateTime.Now.ToString() %></asp:Label>
Set the Label1.Text = value instead of trying to use server side attrs inside of the server control

Validation summary control not showing message?

I have a page with TextBox to enter a Mobile Number.
For that I have validated it using RequiredFieldValidator and RegularExpressionValidator
with display=none:
And also I have placed a ValidationSummary Control
<asp:ValidationSummary ValidationGroup="mobile" ShowSummary="false" ID="vsValid"
runat="server" ShowMessageBox="true" Enabled="true"
DisplayMode="SingleParagraph" />
<asp:TextBox ID="txtMobileNumber" runat="server" CssClass="Qinputbox"></asp:TextBox>
<asp:RequiredFieldValidator Display="None" ControlToValidate="txtMobileNumber"
ID="reqValidMobileNo" runat="server" ErrorMessage="*"
ValidationGroup="mobile"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtMobileNumber" Display="None"
ID="regExValidMobileNo" runat="server"
ErrorMessage="Please enter a valid mobile number."
ValidationExpression="^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9]
(\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$"
ValidationGroup="mobile"></asp:RegularExpressionValidator>
when I entered characters in the TextBox it is not showing the summary.
What might be the problem?
From you code fragment:
ShowSummary="false" Looks like a problem.
You should set either ShowSummary="false" to true or EnableClientScript="true". I'm assuming that you want the latter because you have ShowMessageBox="true".
Have a look: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.validationsummary.enableclientscript%28v=vs.71%29.aspx
Use this property to specify whether
the ValidationSummary control updates
itself using client-side script. When
set to true, client-side script is
rendered on the client to update the
ValidationSummary control, if the
browser supports that feature. When
set to false, no client-side script is
rendered on the client and the
ValidationSummary control only updates
itself on round-trips to the server.
In this situation, the ShowMessageBox
property has no effect.
In web.config setting:
<httpRuntime targetFramework="4.5"/>
This setting turns off Javascript injection of validation (client side).
Remove this and retry.
Ensure that you do NOT have this in the web.config file:
<xhtmlConformance mode="Legacy"/>

debug a CompareValidator (ASP.NET)

What is the best way to debug a CompareValidator that always fails the validation? Is there any way to see what the values are that it's comparing to maybe get a clue as to what's going wrong?
Use Firebug to debug the javascript that .Net inserts
If you are not familiar with the other debugging methods, easiest way for you may be utilizing the Response.Write calls to print the values in your button event to see if they are equal to each other:
Response.Write(TextBox1.Text.ToString().Trim());
Response.Write(TextBox2.Text.ToString().Trim());
Response.End();
Update
For simplicity, I will use CompareValidator to check a data type.
You probably have something similar to the following in your ASPX (client side) code:
<asp:TextBox ID="txtTest" runat="server" />
<asp:CompareValidator ID="cvTest" runat="server"
ControlToValidate="txtTest"
Operator="DataTypeCheck" Type="Date"
Display="Dynamic" ErrorMessage="Incorrect format!" />
<asp:Button ID="btnTest" Text="Test Compare Validator"
onclick="btnTest_Click" runat="server" />
In your codebehind (server side), put the following in your btnTest_Click event to see the value that is entered in txtTest:
Response.Write(txtTest.Text.ToString().Trim());
Response.End();
But keep in mind that there more robust debugging utilities that VS offers. This is just a quick-and-dirty way for your purpose.

Dynamically assigning properties on a non data bound ASP.NET control

For example, let's say I have a HyperLink:
<asp:HyperLink runat="server" Text="Foo" NavigateUrl="foo.aspx" />
How can I set the NavigateUrl on the server side, without having to go the code-behind?
This doesn't work of course:
<asp:HyperLink runat="server" Text="Foo" NavigateUrl="<%= urlString %>" />
(where urlString might be a string I created earlier in the page)
And this doesn't work because the HyperLink is not within a data bound control:
<asp:HyperLink runat="server" Text="Foo" NavigateUrl='<%# urlString %>' />
I guess I could just use a standard anchor element:
Foo
But I'd rather not mix up HTML and ASP.NET controls, and it would be handy to be able to do this for other controls.
Surely there must be a way?
Try setting the property in an inline code block:
<asp:HyperLink runat="server" ID="MyLink" Text="Foo" />
<% MyLink.NavigateUrl="foo.aspx"; %>
This doesn't work of course:
Of course it does.
And this doesn't work because the
HyperLink is not within a data bound
control:
Consider the Page as your data bound control.
You need to calls it's DataBind method.
Page.DataBind();
Maybe you need to add an ID attribute as well. If that does not work, try to display a property instead of a variable.

What do you suspect when ASP.NET ignores a CustomValidator?

This is as much a code maintenance issue as a code issue, but I have a WebForm that no longer checks it CustomValidator. It worked when I last touched the code over a year ago, but it no longer works now that the user has requested some changes ...
The WebForm contains a data-bound drop down with a default " - All -" item with String.Empty as its value. When the user clicks the submit button, the validator should check that the drop down's value is not String.Empty. I've set break points in the client validation code and the server validation code, but neither fire.
Where would you start looking? What are the usual suspects? I have, of course, compared my working copy to what is in source control, but nothing jumps out as being suspicious.
Just in case it matters, here is my code:
<asp:DropDownList ID="_AssessmentDropDown" runat="server" DataSourceID="_AssessmentsData" CausesValidation="true" AutoPostBack="false"
DataTextField="AssessmentName" DataValueField="AssessmentName" OnDataBound="_HandleAssessmentsBound">
</asp:DropDownList>
<asp:CustomValidator ID="_AssessmentValidator" runat="server" ClientValidationFunction="_HandleValidateAssessment_Client"
ControlToValidate="_AssessmentDropDown" ErrorMessage="* You must select an Assessment."
OnServerValidate="_HandleValidateAssessment" />
<asp:ObjectDataSource ID="_AssessmentsData" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="DataTableAdapters.GET_GRADE_ASSESSMENTSTableAdapter">
<SelectParameters>
<asp:ControlParameter Name="GRADECODE" ControlID="_GradeCodeDropDown" PropertyName="SelectedValue" />
</SelectParameters>
</asp:ObjectDataSource>
I notice a couple of issues
I don't think you need a CausesValidation=true if AutoPostBack is set to false
You do not use validation groups, so that cannot be the cause
Why not use a RequiredFieldValidator?
If you want to fire validation on empty fields, set the ValidateEmptyText property to true
A CustomValidator doesn't fire if the control it is validating has an empty value, so a CustomValidator should always be accompanied by RequiredFieldValidator
Some troubleshooting steps:
Is this the only validator on the form?
Is validation enabled on the page?
Is validation enabled for the targeted control?
Is the validator itself enabled?
I would take a serious look at the ValidationGroup.
If something has been left out of the group, it wouldn't validate anymore. Otherwise, make sure that you don't have any javascript error (for the client side) and that the method that is "OnServerValidate" has a break point inside.
Is the validator in the same validator group as the submit button?

Resources