I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}
Related
I have a listview that populates with data. This listview is inside a user control which sits inside a page called Preferences.aspx. Today I am handling click event on each row meaning that involves posting back to server.
Now, I have to put another user control on Preferences.aspx because there are group of more settings which need to be presented separately to users. I have added the new user control inside a separate tab on the page. This new tab has to be the first one to show when user lands on Preferences.aspx.
Now the problem is that when user goes to second tab (user control with listview) and click on a row, a postback occurs. This puts the user on the first tab (newly added user control).
So I wonder how can I get click event on a row without having to postback?
Any ideas or suggestions are welcome.I am working in Asp.Net with C#.
The code is:
Markup inside the user control:
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
... and so on
Markup inside Preferences.aspx:
<ABC:ListControl runat="server" ID="visitorListControl" CanSelect="true" IsMine="true" Recurring="false" OnVisitorSelected="ListControl_VisitorSelected" />
And code behind is:
protected string GetClickPostBack(int itemIndex)
{
if (CanSelect)
//return 0.ToString();
return "javascript: " + Page.ClientScript.GetPostBackEventReference(this, VisitorRowPrefix + itemIndex) + "; return false;";
else
return string.Empty;
}
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith(VisitorRowPrefix))
{
HandleRowClick(Convert.ToInt32(eventArgument.Substring(VisitorRowPrefix.Length)));
}
}
private void HandleRowClick(int index)
{
int CmgVisitorId = Constants.NotConfigured;
// bool IsHistoricVisitor = false;
// Visitor HistoricVisitor = new Visitor();
// Mark only the clicked row
... and so on.
Hook up to the grid button's click event using JavaScript/jQuery, and prevent theirs default behaviour (post-back) by 2 possible means:
return false;
e.preventDefault (jQuery only)
Example (using jQuery):
$('.button').click(function(event){
event.preventDefault();
//Write your client-side logic here
});
Description: If this method is called, the default action of the event
will not be triggered.
If I am understanding the issue properly, try an update panel.
Check out the documentation here.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
</ContentTemplate>
</asp:UpdatePanel>
Before submitting the form I need to test if the sum ( txtA + txtB) is greater than 100. Is it possible to do this with a CustomValidator, because I don't know if I can choose the 2 textbox in controltovalidate
<asp:TextBox ID="txtA" runat="server"></asp:TextBox>
<asp:TextBox ID="txtB" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator" />
<asp:Button ID="Button1" runat="server" Text="Button" />
Thanks.
you can do as :
<asp:TextBox ID="txtA" runat="server" />
<asp:TextBox ID="txtB" runat="server" />
<asp:CustomValidator ID="CV1"runat="server"
OnServerValidate="ServerValidation"
ErrorMessage="Sum is less than 100" />
codebehind :
protected void ServerValidation(object source, ServerValidateEventArgs args)
{
args.IsValid = int.Parse(txtA.Text)+ int.Parse(txtB.Text) >100;
}
When you drop a custom validation in your page, you can link the validator to a control, but if you want to perform multiple validations over more than one control, you need to include the following attribute
OnServerValidate="MyMethodOnServerSide"
and define that method on the server side
protected void MyMethodOnServerSide(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrEmpty(mytxt1.Text) &&
string.IsNullOrEmpty(mytxt2.Text))
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
just asign the args.IsValid property to the value you need. On the other hand the validation is done before you load the page, so if you clicked a button that performs an action like reading values from the DB in case everything is correct, on that action you need to include the following check.
protected void cmdSearch_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
LoadDataFromDB();
}
}
When args.IsValid is false then Page.IsValid is false too. Hope this helps
You need to add another control, <asp:HiddenField> and then leverage jQuery to set the value of that control. It might look something like this:
MARKUP
<asp:HiddenField ID="SumOfValues" />
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator"
ControlToValidate="SumOfValues" />
JQUERY
$(document).ready(function() {
$('#txtA').change(sumValues);
$('#txtB').change(sumValues);
});
function sumValues() {
var val1 = $('txtA').value();
if (val1 === undefined) { val1 = 0; }
var val2 = $('txtB').value();
if (val2 === undefined) { val2 = 0; }
$('#SumOfValues').value(val1 + val2);
}
and that should allow you validate that hidden control. However, one thing you'll need to make sure to do on all three controls is leverage ClientIDMode and set it to Static so that the names are exactly what you specify in the markup when they get to the page.
I have an asp page with some Textbox controls on it.
By default, the browser will suggest previously entered values for each box.
I'd like to prevent that behavior for some of the textboxes.
Is there a way to reliably do that across all major browsers?
I've tried setting
AutoCompleteType="Disabled"
But that seems to have no effect in Firefox.
Here is an image of the behavior I'm trying to prevent.
For firefox
Either:
<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>
Or from the CodeBehind:
Textbox1.Attributes.Add("autocomplete", "off");
Autocomplete need to set off from textbox
<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"></asp:TextBox>
By making AutoCompleteType="Disabled",
<asp:TextBox runat="server" ID="txt_userid" AutoCompleteType="Disabled"></asp:TextBox>
By setting autocomplete="off",
<asp:TextBox runat="server" ID="txt_userid" autocomplete="off"></asp:TextBox>
By Setting Form autocomplete="off",
<form id="form1" runat="server" autocomplete="off">
//your content
</form>
By using code in .cs page,
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txt_userid.Attributes.Add("autocomplete", "off");
}
}
By Using Jquery
<head runat = "server" >
< title > < /title> < script src = "Scripts/jquery-1.6.4.min.js" > < /script> < script type = "text/javascript" >
$(document).ready(function()
{
$('#txt_userid').attr('autocomplete', 'off');
});
//document.getElementById("txt_userid").autocomplete = "off"
< /script>
and here is my textbox in ,
<asp:TextBox runat="server" ID="txt_userid" ></asp:TextBox>
By Setting textbox attribute in code,
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txt_userid.Attributes.Add("autocomplete", "off");
}
}
This is the answer.
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
AutoCompleteType="Disabled"
If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go
'Options' --> 'Security'(tab) --> Untick
'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.
This should solve the problem
Trying from the CodeBehind:
Textbox1.Attributes.Add("autocomplete", "off");
Adding autocomplete="new-password" to the password field did the trick. Removed auto filling of both user name and password fields in Chrome.
<input type="password" name="whatever" autocomplete="new-password" />
Please note that for Chrome to work properly it needs to be autocomplete="false"
This works for me
<script type="text/javascript">
var c = document.getElementById("<%=TextBox1.ClientID %>");
c.select =
function (event, ui)
{ this.value = ""; return false; }
</script>
I have a form with some custom validation. There is a button on the form that should take the user to a 'confirm page' to show all the details of an order.
On-Page Validation
<asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName"
runat="server" CssClass="txtbxln required"></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorBillLN" runat="server"
ControlToValidate="txtBillingLastName"
OnServerValidate="CustomValidatorBillLN_ServerValidate"
ValidateEmptyText="True">
</asp:CustomValidator>
Validator code behind
protected void CustomValidatorBillLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = isValid(txtBillingLastName);
}
However, if I add PostBackUrl or Response.Redirect to the button onclick method, all the validation controls are ignored.
I could call all the validation methods with the onclick method, but that seems a less than an elegant solution.
I've tried setting CausesValidation=False with no luck.
Any suggestions?
Of course that validation IS ignored if you redirect unconditionally. You should call this.IsValid before you redirect like
protected btRedirect_Click( object sender, EventArgs e )
{
if ( this.IsValid )
Response.Redirect( ... );
}
Check this code
void ValidateBtn_OnClick(object sender, EventArgs e)
{
// Display whether the page passed validation.
if (Page.IsValid)
{
Message.Text = "Page is valid.";
}
else
{
Message.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i%2) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
And Html side code
<form id="Form1" runat="server">
<h3>CustomValidator ServerValidate Example</h3>
<asp:Label id="Message"
Text="Enter an even number:"
Font-Name="Verdana"
Font-Size="10pt"
runat="server"/>
<p>
<asp:TextBox id="Text1"
runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<p>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
For further information check Custom validator
Hope my answer help you to solve your problem.
I have an AJAX ToolKit TabContainer control with several TabPanels. I want to validate the contents of the current active TabPanel to prevent user from working on other ones in case data was invalid.
If you need to do a TabPanelChangingEvent SERVER side, You will need to do this by Altering the ajaxcontroltoolkit Source code.
Good news : you could easily get it
Here a new solution that does almost what your need :
The OnClientActiveTabChanged event is raised
The tabcontainer New Tab index is saved in a Hiddenfield
The tabindex is reset to it's old value (so it wont change right now)
The form trigger a asyncpostback using a hidden button.
Within the hidden button's Click event, the OldTabIndex and NewTabIndex are retrieved.
At the end of the Click event, the tabcontainer's tabindex is switched to the new value.
So, the hidden button's Click event is executed before the TabContainer tab is changed.
aspx:
<asp:Button runat="server" ID="hiddenTargetControlForTabContainer" style="display:none" />
<asp:UpdatePanel ID="TabContainerUpdatePanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="hiddenTargetControlForTabContainer" />
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="TabContainerActiveTab" runat="server" Value="0" />
<AjaxControlToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"
OnClientActiveTabChanged="OrderTabContainerClientActiveTabChanged" >
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel1"
HeaderText="TabPanel1"
>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel2"
HeaderText="TabPanel2" >
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
</AjaxControlToolkit:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
var TabContainerActiveTabControlID = '<%= TabContainerActiveTab.ClientID %>';
var hiddenTargetControlForTabContainerControlID = '<%= hiddenTargetControlForTabContainer.uniqueID %>';
function OrderTabContainerClientActiveTabChanged(sender, args) {
var TabContainerActiveTabControl = $get(TabContainerActiveTabControlID);
var OldtabIndex = parseInt(TabContainerActiveTabControl.value);
var NewtabIndex = sender.get_activeTabIndex();
if (!(OldtabIndex == NewtabIndex)) {
sender.set_activeTabIndex(OldtabIndex);
TabContainerActiveTabControl.value = NewtabIndex;
__doPostBack(hiddenTargetControlForTabContainerControlID, '');
}
}
Code behind:
Protected Sub hiddenTargetControlForTabContainer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles hiddenTargetControlForTabContainer.Click
Dim oldActiveTabIndex = TabContainer1.ActiveTabIndex
Dim newActiveTabIndex As Integer = Convert.ToInt32(TabContainerActiveTab.Value)
'your stuff here
TabContainer1.ActiveTabIndex = newActiveTabIndex
End Sub
Problem: Ajax TabContainer the ActiveTabChanged event shows incorrect ActiveTabIndex.
For eg. TabContainer contain 3 tabs, if second tab is hide(visible = false on server side) then on click of third tab, we get ActiveTabChanged = 1 not 2 (expected active index is 2 on server side code).
Solution:
Register the clientside event of the tab container:
OnClientActiveTabChanged="Tab_SelectionChanged"
Then define the javascript function to handle the above event which will internally store the tab index in a hidden variable.
function Tab_SelectionChanged(sender,e)
{
document.getElementById('<%=hdntabIndex.ClientID %>').value = sender.get_activeTabIndex();
}
Use the hidden variable(hdntabIndex) in the code behind where ever you need the active tab index.
You should do it using JavaScript.
Here an example I made, the trick is to use ValidationGroup and save the Old tab Index at the end of the function called by the OnClientActiveTabChanged
<AjaxControlToolkit:TabContainer ID="TabContainer1" runat="server" Height="138px"
Width="402px" ActiveTabIndex="0"
OnClientActiveTabChanged="ValidateTab" >
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel1"
HeaderText="TabPanel1"
>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="TextBox1"
ValidationGroup="TabPanel1"
/>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel2"
HeaderText="TabPanel2" >
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="TextBox2"
ValidationGroup="TabPanel2"
/>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
</AjaxControlToolkit:TabContainer>
<script type="text/javascript">
var OldtabIndex = 0;
function ValidateTab(sender, args) {
if (OldtabIndex == 0) {
if (!Page_ClientValidate('TabPanel1')) {
sender.set_activeTabIndex(OldtabIndex);
}
}
else if (OldtabIndex == 1) {
if (!Page_ClientValidate('TabPanel2')) {
sender.set_activeTabIndex(OldtabIndex);
}
}
OldtabIndex = sender.get_activeTabIndex();
}
</Script>
I know I'm probably late to answering this question, but hopefully, I can offer some assistance to someone who's pot-committed like I was to the TabPanels.
Add the OnClientActiveTabChanged="showMap" to the ajaxToolkit:TabContainer. My function is obviously called showMap (had to hide and show the Google Street Map, because TabContainer screws it all up. So I had to move the Google Street Map outside of the container and then 'fake' put it back in the container).
<ajaxToolkit:TabContainer runat="server" ID="tabs" OnClientActiveTabChanged="showMap">
<ajaxToolkit:TabPanel runat="server" ID="pnlZones" HeaderText="Delivery Zones">
<ContentTemplate>
...
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
Then create the javascript:
<script type="text/javascript">
function showMap() {
var tabID = $('.ajax__tab_active').attr('id');
if (tabID.indexOf('pnlZone') > 0) {
$('#mapHider').css('height', '600px');
}
else {
$('#mapHider').css('height', '0');
}
}
</script>
We can then find the active tab by the class .ajax__tab active, which is what TabContainer will set the active class to. Snag the ID (.attr('id')) with jQuery... And voila, we now which tab we're currently on.
For this I change the height of the class from 0 to 600px. With the overflow set to hidden, it makes it seem like the map is on the page and only in that container, but it isn't.
Hopefully, this helps!! Good luck.