handling enter press in <asp:textbox - asp.net

I have an asp.net textbox which I want to use as a search box.
I wasn't planning on having a button, just allowing the user to type their search keywords into the textbox and press enter.
<div id="search-bar">
<asp:TextBox ID="txtSearch" runat="server" ></asp:TextBox>
</div>
How can I get the "enter press" to call a method, or post back the page with keywords in URL parameters, e.g. search.aspx?keywords=this&that?

Set AutoPostback to true if you want to call a function in codebehind OnTextChanged. This will occur if the Textbox loses focus(f.e. Tab-key) or Enter-Key is pressed.

There are other ways you can set a default button using the form object DefaultButton property or the DefaultButton property of a panel, but I have found them to be unreliable in the past in various browsers so usually I rely on javascript, if you don't want the button visible you can just set the visible property to false.
The only downside to this code is you have to turn off event validation with a page directive, but it should fire off click events, and trigger validators and all that.
Here is an example the code that we use. Normally I would put the register function in a utility class, but for this example it is in the page code.
<%# Page Language="C#" EnableEventValidation="false" %>
<script runat="server">
protected void cmdSubmit1_Click(object sender, EventArgs e)
{
litValue.Text = "Value 1 - You entered: " + txtValue1.Text;
}
protected void cmdSubmit2_Click(object sender, EventArgs e)
{
litValue.Text = "Value 2 - You entered: " + txtValue2.Text;
}
/// <summary>
/// This function registers what button is clicked based on whatever control currently has focus
/// so for example if the user password field has focus then you can cause the enter button to click
/// if the enter key is pressed This works with ie and firefox as far as I know
/// </summary>
/// <param name="ControlWithFocus"></param>
/// <param name="ControlToClick"></param>
private void RegisterDefaultButton(System.Web.UI.Control ControlWithFocus, System.Web.UI.Control ControlToClick)
{
PostBackOptions p = new PostBackOptions(ControlToClick);
p.PerformValidation = true;
if (ControlToClick is Button)
{
p.ValidationGroup = ((Button)ControlToClick).ValidationGroup;
}
else if (ControlToClick is ImageButton)
{
p.ValidationGroup = ((ImageButton)ControlToClick).ValidationGroup;
}
else if (ControlToClick is LinkButton)
{
p.ValidationGroup = ((LinkButton)ControlToClick).ValidationGroup;
}
p.RequiresJavaScriptProtocol = false;
AttributeCollection a = null;
if (ControlWithFocus is HtmlControl)
{
a = ((System.Web.UI.HtmlControls.HtmlControl)ControlWithFocus).Attributes;
}
else if (ControlWithFocus is WebControl)
{
a = ((System.Web.UI.WebControls.WebControl)ControlWithFocus).Attributes;
}
if (a != null)
{
a["onKeyDown"] = string.Format("if (event.keyCode == 13) {{{0}}}"
, ControlToClick.Page.ClientScript.GetPostBackEventReference(p));
}
}
protected void Page_Load(object sender, EventArgs e)
{
RegisterDefaultButton(txtValue1, cmdSubmit1);
RegisterDefaultButton(txtValue2, cmdSubmit2);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
Enter Value 1: <asp:TextBox ID="txtValue1" runat="server"></asp:TextBox>
<br />
Enter Value 2: <asp:TextBox ID="txtValue2" runat="server"></asp:TextBox>
<br />
<asp:Literal ID="litValue" runat="server"></asp:Literal>
<asp:LinkButton ID="cmdSubmit1" runat="server" Visible="false" OnClick="cmdSubmit1_Click">Hidden Button 1</asp:LinkButton>
<input id="cmdSubmit2" runat="server" visible="false" type="button" value="Hidden Button 2" onserverclick="cmdSubmit2_Click" />
</form>
</body>
</html>

to submit a form with javascript is:
document.forms["myform"].submit();
but asp usually puts a whole bunch of javascript in the click for buttons to do with viewstate and things like that, so you might be better off adding a button that is set as the default for the form, and then hiding it with CSS.

Related

How to stop dropdownlists where autopostback true, from posting to a new page set in postbackurl of button ASP.NET

The page performs as intended locally, the problem is when I upload to windows server and access it from there.
I have 2 to 3 dropdownlists displayed (depending on whats selected in the first dropdownlist)....
The first 2 dropdownlists where autopostback is set to true, will autopostback to the same page (intended performance). However, after I click the button within the form, and go back to original page, whenever there is a selectedindexchanged event on those dropdownlists, those dropdownlists are not autopostback to the same page anymore, they will now post to the postbackurl declared in the button (this is unintended and not the desired results)
How can I get those dropdownlists to stop from posting to new page on selectedindexchanged after I click the button and go back to original page?
Again, the dropdownlists do not autopostback to a new page until I click the button and then go back to that original page. At that point they then post to the postbackurl that is declared in the button. I don't understand why this is happening.
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder1" runat="server">
<div style="text-align: center">
<asp:Label ID="Label1" runat="server"></asp:Label>
<form id="form1" runat="server">
<asp:DropDownList ID="toolGroupDropDown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="toolgroupddl_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="sizeDropDown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="sizeddl_SelectedIndexChanged" Visible="False">
</asp:DropDownList>
<asp:DropDownList ID="attDropDown" runat="server" Visible="False">
</asp:DropDownList><br />
<asp:Button ID="seeToolsButton" runat="server" Text="See Tools" Visible="False" PostBackUrl="/products" />
</form>
</div>
</asp:Content>
Here is some code-behind, not sure if this is relevant though...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing
{
public partial class WebForm12 : System.Web.UI.Page
{
public string listing;
public string attsize;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FillDropDown();
}
else
{
System.Diagnostics.Debug.WriteLine("postback occured");
}
}
protected void toolgroupddl_SelectedIndexChanged(object sender, EventArgs e)
{
listing = toolGroupDropDown.SelectedValue;
sizeDropDown.DataSource = this.GetSizeRecords();
sizeDropDown.DataTextField = "groups";
sizeDropDown.DataValueField = "groups";
sizeDropDown.DataBind();
sizeDropDown.Visible = true;
seeToolsButton.Visible = true;
toolGroupDropDown.Items.Remove(toolGroupDropDown.Items.FindByValue(""));
if (toolGroupDropDown.SelectedValue != "END")
{
sizeDropDown.AutoPostBack = false;
attDropDown.Visible = false;
sizeDropDown.Items.Insert(0, new ListItem("Choose Your Size", ""));
}
else
{
attDropDown.Visible = true;
sizeDropDown.AutoPostBack = true;
sizeDropDown.Items.Insert(0, new ListItem("Choose Your Size", ""));
}
}
protected void sizeddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (toolGroupDropDown.SelectedValue == "END")
{
attDropDown.DataSource = this.GetAtts(attsize);
attDropDown.DataTextField = "NoOfAtts";
attDropDown.DataValueField = "NoOfAtts";
attDropDown.DataBind();
attDropDown.Visible = true;
}
else
{
attDropDown.Visible = false;
}
}
}
}
I only posted the code-behind that seemed relevant. Nothing else in the code relates to the question at hand.
The problem is page changing the action attribute. At Html level, initially you have:
<form method="post" id="form1" action="./WebForm12">
So dropdowns correctly post back to WebForm12. But when you press the button.
<asp:Button ID="seeToolsButton" runat="server" PostBackUrl="/products" />
The page does two things using Javascript:
Change the action attribute of the form to "/products".
Post the form.
When you navigate back in your browser, the form looks like this
<form method="post" id="form1" action="/products">
But now, dropdowns will post the form to /products, not WebForm12.
Solution: One way to fix that is adding this script to your aspx file
<script type="text/javascript">
window.onpageshow = function () {
form1.action = "./<%=System.IO.Path.GetFileName(Request.Url.AbsolutePath)%>";
};
</script>
However if your browser does not support onpageshow (e.g. IE10 or older), then you'd rather attach the function to click event of the dropdowns.

How do I load two ASP.NET UserControls on Demand?

I want load two user controls on demand.
asp:UpdatePanel ID="UpdatePanel1" runat="server"
ContentTemplate
asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button1_Click" /
div id='Div_UserControlPlace' enableviewstate="true" runat="server"
/div
/ContentTemplate
Triggers
asp:PostBackTrigger ControlID="Button1" /
/Triggers
/asp:UpdatePanel
asp:UpdatePanel ID="UpdatePanel2" runat="server"
ContentTemplate
asp:Button ID="Button2" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button2_Click" /
div id='Div_UserControlPlace2' enableviewstate="true" runat="server"
/div
/ContentTemplate
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl = new Control();
FeaturedProductUserControl = LoadControl("WebUserControl1.ascx");
FeaturedProductUserControl.EnableViewState = true;
Div_UserControlPlace.Controls.Add(FeaturedProductUserControl);
}
protected void Button2_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl2 = new Control();
FeaturedProductUserControl2 = LoadControl("WebUserControl2.ascx");
FeaturedProductUserControl2.EnableViewState = true;
Div_UserControlPlace2.Controls.Add(FeaturedProductUserControl2);
}
I load the first user control by clicking on the first button - this works properly but when I click on the other button to load the second UserControl, the first UserControl disappears and the second UserControl loads.
Thanks
IFA_User
You should use the Placeholder control to dynamically add your controls to the form.
Take a look at my last responses about dynamic controls:
OnClick event of dynamically created LinkButtons is not working
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
Dynamically create an ImageButton
Now I already have some code working for demo purpose, each dynamic user controls keeps its state across post backs
This is the output:
ASPX
<asp:PlaceHolder runat="server" ID="addresses" /><br />
<asp:Button Text="Add Address" runat="server" ID="addAddress" OnClick="addAddress_Click" />
ASPX Code behind
protected void Page_PreLoad(object sender, EventArgs e)
{
for (int i = 0; i < this.DynamicControlsCount; i++)
{
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
}
protected void addAddress_Click(object sender, EventArgs e)
{
this.DynamicControlsCount++;
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
protected int DynamicControlsCount
{
get
{
if (this.ViewState["ac"] == null)
{
return 0;
}
return (int)this.ViewState["ac"];
}
set
{
this.ViewState["ac"] = value;
}
}
ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressControl.ascx.cs" Inherits="WebApplication1.AddressControl" %>
<asp:Panel ID="Panel1" runat="server" GroupingText="Address" DefaultButton="btnSave">
Street: <asp:TextBox runat="server" ID="txtStreet" /><br />
City: <asp:TextBox runat="server" ID="txtCity" /><br />
<asp:Button Text="Save" runat="server" ID="btnSave" OnClick="btnSave_Click" />
</asp:Panel>
<asp:Panel runat="server" GroupingText="Address Summary" Visible="false" ID="summary">
<asp:Label ID="lblStreet" runat="server" /><br />
<asp:Label ID="lblCity" runat="server" />
</asp:Panel>
ASCX Code behind
protected void btnSave_Click(object sender, EventArgs e)
{
this.summary.Visible = true;
this.lblCity.Text = "Selected city: " + this.txtCity.Text;
this.lblStreet.Text = "Selected street: " + this.txtStreet.Text;
}
When a user control is created in the HTML, asp.net will persist across postbacks without any user interaction. But if you are loading them programatically (dynamically), they will not persist accross postbacks. So if you load them programmatically, you have the added task of persisting them programmatically as well. Use the ViewState (or Session I suppose) to store what has been loaded and perhaps any other necessary information that needs to be loaded between postbacks. Every single postback will require you to reload every control or else they will disappear.
There are couple of ways of doing it:
U can load the UserControls using Ajax. Benefit of using Ajax, is ur page does not get post back, thus for example, on click event of Button1, call a ajax(traditional/Jquery) to load UserControl1, and on button click of Button2 User control2.
Put the two button in two different updated panel, by doing this the click event will only refresh a part of ur page.
U have to save somewhere (ViewState/Session),which buttons are clicked, and upon clicking of any button check the value of that variable, and explicit load the control.
Points to note - If u want to get ur data back when ur page made a complete postback, then u have to add the controls keeping in mind the Page load event cycle.

ASP javascript radiobutton enable disable not included in postback ajax

Here is the problem. I have a radiobutton group (two radiobuttons).
These guys are initialy disabled. When the user clicks a checkbox, I dynamically enable radiobuttons in javascript by setting rbtn.disabled = false; and doing the same for it's parent (span element) so it correctly works in IE.
The problem is that these dynamically enabled radiobuttons are not returned on postback (I see rbtn.Checked == false on serverside and request.form does not contain proper value).
Why is this happening? Is there another fix except for a workaround with hidden fields?
Expected answer decribes post-back policy, why/how decides which fields are included in postback and fix to this problem.
Before doing the submit, remove the disabled attribute from the radio buttons like this:
document.getElementById("rbtnID").removeAttribute("disabled");
Note that removeAttribute can be buggy in IE, and IE also implements a second attribute for case sensitivity, see MSDN article.
There is also removeAttributeNode which removes the entire attribute node, but it takes the node itself as the parameter instead of the name.
var disabledNode = element.getAttributeNode('disabled');
element.removeAttributeNode(disabledNode);
So give these a shot and let me know how they play out!
I know the following code is not neat, but it gets the job done (if I understand the problem correctly). I copy/paste here the whole file contents to make it easier for you to play with it. Just create a web form named WebForm1 and paste these;
in .aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function enable(sender) {
if (sender.checked) {
document.getElementById('<%= RadioButton1.ClientID %>').removeAttribute('disabled');
document.getElementById('<%= RadioButton2.ClientID %>').removeAttribute('disabled');
}
else {
document.getElementById('<%= RadioButton1.ClientID %>').disabled = true;
document.getElementById('<%= RadioButton2.ClientID %>').disabled = true;
}
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" onclick="enable(this)" />
<asp:RadioButton ID="RadioButton1" runat="server" Text="1"
Enabled="false" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="2"
Enabled="false" />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click1" />
<asp:Label ID="Label1" runat="server" Text="" />
</form>
</body>
</html>
in .aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
static readonly string GROUP_NAME = "RadioButtonGroup";
protected void Page_Load(object sender, EventArgs e)
{
RadioButton1.GroupName = GROUP_NAME;
RadioButton2.GroupName = GROUP_NAME;
if (IsPostBack)
{
if (CheckBox1.Checked)
{
RadioButton1.Enabled = true;
RadioButton2.Enabled = true;
if (Request.Params[GROUP_NAME] == RadioButton1.ID)
{
RadioButton1.Checked = true;
}
else if (Request.Params[GROUP_NAME] == RadioButton2.ID)
{
RadioButton2.Checked = true;
}
}
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (Request.Params[GROUP_NAME] == RadioButton1.ID)
{
Label1.Text = "1 is selected";
if (Request.Params[GROUP_NAME] == RadioButton2.ID)
{
Label1.Text += "and 2 is selected";
}
}
if (Request.Params[GROUP_NAME] == RadioButton2.ID)
{
Label1.Text = "2 is selected";
}
}
}
}
I haven't had a chance to test this myself, but I'm guessing (if your using ASP.net), that your disabling the radio buttons via the ASP.net server-side code i.e via a server side control.
And then renabling them using javascript?
I think perhaps that the server-side still believes they are disabled - I'm not 100% why without digging futther (something in the page lifecycle somewhere).
Perahaps a quick solution would be instead of disabling the radio buttons via server-side, instead disable them in javascript when the page loads? i.e. doing the disabling and enabling in javscript.
Before submitting the page set the disabled property of the radios buttons to false. In the code behind read the radio button value using Request.Form["radioButtonName"]. This will give you the value of the radio button which is checked.
Example:
Let say the radio button list name is radioButton1 with 2 radio buttons. When it renders on the page the radio buttons will have the same name say ctl0$radioButton1. Anyways it depends on the nesting of your page. You can get this name using radioButton.UniqueID.
When the page is submitting through any action on the page execute the below javascript which will set the disabled property of the radio button to false.
document.getElementById("radioButton1ItemCliendId").disabled = false;
//If you want to check this radio button then
document.getElementById("radioButton1ItemCliendId").checked = true;
On the server side postback event handler you have to use Request.Form[radioButton1.UniqueID] to get this radio buttons value. It will give the radio buttons value which is checked.

Required field validator for multiple dropdown lists in an aspx page

I have an aspx page which has 18 (yes 18) dropdown lists and 18 text boxes. Each dropdown needs to be selected and each textbox needs to be filled. Dragging and dropping required field validators on these 36 controls and maintaining them is a painful task and does not seem to be the logical option as all I need is for the user to select a value from the dropdown.
Is there anyway I can loop through all these dropdown controls and textbox controls, check if they are empty and display warnings to users accordingly? Client-side validation solution or server side validation solution is fine with me.
Use a CustomValidator and have a client script function that makes sure every text box/drop down has a value.
One suggestion is to loop through all the controls on the page, use recursive function to dynamically bind RequiredFieldValidator to the found controls. You can tweak my code to suit your needs.
This code has some drawbacks though:
Use control.ID instead of associated label text
Adding RequiredFieldValidator to the page.controls will modify its ControlCollection. This will break the foreach method. Thus, I can only add RequiredFieldValidator to Panel instead.
.aspx
<asp:Panel ID="pnlValidation" runat="server">
</asp:Panel>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" />
<asp:DropDownList ID="DropDownList2" runat="server" />
<asp:DropDownList ID="DropDownList3" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
.cs
protected void Page_Load(object sender, EventArgs e)
{
AddValidator(this);
}
private void AddValidator(Control ctrl)
{
if (ctrl is TextBox || ctrl is DropDownList)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = ctrl.ID;
rfv.Display = ValidatorDisplay.Dynamic;
rfv.ErrorMessage = ctrl.ID + " is required<br />";
pnlValidation.Controls.Add(rfv);
}
foreach (Control subctrl in ctrl.Controls)
AddValidator(subctrl);
}
If you are dynamically generating the textboxes and dropdownlists, you would probably want to dynamically generate the validation controls as well, but if all the drop down lists and textboxes are static you can use the following:
Use a CustomValidator Web Control, write client side javascript method that checks all the properties of the drop down lists and the textboxes and configure the web control's ClientValidationFunction with the function and set EnableClientScript=true. Also, b/c not all users have javascript enabled, plus to be sure as it is best practice, always also create a server side validation function as well and call Page.IsValid() on the submit action.
.aspx Sample Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs"
Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function ValidateMe(sender, args) {
var txt = document.getElementById("txt");
if (txt.value != "")
args.IsValid = true;
else
args.IsValid = false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox id="txt" runat="server" />
<asp:CustomValidator ClientValidationFunction="ValidateMe" ID="custval"
runat="server" ErrorMessage="Fail" onservervalidate="custval_ServerValidate" />
<asp:Button ID="btn" runat="server" Text="push" onclick="btn_Click1" />
</form>
</body>
</html>
c# codebehind sample code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btn_Click1(object sender, EventArgs e)
{
if (Page.IsValid)
{
btn.Text = "PASS";
}
else
{
btn.Text = "FAIL";
}
}
protected void custval_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txt.Text != "")
custval.IsValid = true;
else
custval.IsValid = false;
}
}

Page.IsValid always returning true with ValidationGroup and dynamic CustomValidator

I am adding a custom validator to the page programmatically on click of a button, then validating the page and checking the IsValid property of the page. but the IsValid property is always returning true. Please help. here is the code. I need to add custom validator dynamically to show validation messages from business object. I am setting the IsValid property of the custom validator to false, so I expect the IsValid property of the Page to return false as well after validation. can't understand what I am doing wrong here.
protected void Button1_Click(object sender, EventArgs e)
{
var validator = new CustomValidator();
validator.IsValid = false;
validator.ErrorMessage = "The input is invalid";
validator.ValidationGroup = "vgCustom";
Page.Validators.Add(validator);
ValidationSummary1.ValidationGroup = "vgCustom";
Page.Validate("vgCustom");
Label1.Text = Page.IsValid ? "The Page is valid" : "The Page is Invalid";
}
and here is the HTML mark-up
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
i had the same problem with RequiredFieldValidator (Page.IsValid was always true)
i had a panel i wanted to show only when validation is false:
<asp:Panel ID="PanelValidationMessage" CssClass="hide messegeFailed" runat="server">
<p><asp:RequiredFieldValidator ID="RequiredFieldValidatorProductForTransfer"
runat="server"
ValidationGroup="Transfer"
ErrorMessage="Please Select Product for Transfer"
ControlToValidate="DDLProductForTransfer"
InitialValue="0"
SetFocusOnError="true"
Display="Dynamic"></asp:RequiredFieldValidator></p>
</asp:Panel>
it was resolved after i changed the "CausesValidation" attribute of the button from "true" to "false":
<asp:Button ID="BtnTransfer"
runat="server"
Text="Transfer Products"
onclick="BtnTransfer_Click"
ValidationGroup="Transfer"
CausesValidation="false"/>
code behind:
Page.Validate("Transfer");
if (Page.IsValid)
{
PanelValidationMessage.CssClass = "hide messegeFailed";
}
else
{
PanelValidationMessage.CssClass = "show messegeFailed";
}
#James is incorrect you need to add the CausesValidation="true" to your button.
BaseValidator.Validate Method:
Use the Validate method to perform
validation on the associated input
control. This method allows you to
programmatically perform validation on
the input control. The IsValid
property is automatically updated with
the validation results.
So validator.IsValid is being reset to its default value (True) when you call Page.Validate("vgCustom"). Whereas with the ServerValidateEventHandler, your code is setting IsValid on Page.Validate("vgCustom") instead of letting it be reset to the default. If you move validator.IsValid = false to after the call to Page.Validate("vgCustom"), the page should fail to validate as expected.
I prefer to use the following pattern though:
/// <summary>
/// A validator that fails unconditionally. Useful if you need to do
/// validation entirely in the code-behind, yet still integrate with
/// the standard ASP.NET validation framework.
/// </summary>
public class FailValidator : BaseValidator {
protected override bool ControlPropertiesValid() {
// make setting ControlToValidate optional
return true;
}
protected override bool EvaluateIsValid() {
return false;
}
}
You need to add the validationgroup to the button to trigger it
First, I think it is easier to add the validator in your aspx, instead of code-behind. it will be hidden anyways at first.
Second, set OnServerValidate="myControl_OnServerValidate" attribute on the in your aspx.
Then, in your code-behind implement myControl_OnServerValidate(): your validation code there can set the validator.IsValid to false. When the Page validates, it will automatically aggregate the value from your validator, and the Page.IsValid will be set to false by the Page implementation
NOTE, client validation runs, and if all goes well on client, then server validation runs (please see https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx#Remarks)

Resources