how to disable server side validation on asp.net web forms from browser? - asp.net

I wanted to disable asp.net validation server controls from browser. I checked online but did not find any way to disable the server side validation; it can be disabled only on the client side using JS/jQuery.
Here is the scenario: I have a checkbox and selecting which displays a set of text boxes. Only if the checkbox is checked, required field validator should fire for the text boxes. I don't want to call a postback on checkbox. Actually those chceck boxes will be generated with jQuery templating so postback is not an option to enable disable validtion.
I would like to know whether there is any way we can enable disable the .CausesValidation property for the controls from browser using some setting? Or is there a way to capture the controls which are to be considered for validation slectively in some event before page_load?
[Update]
Based on Accepted answer, here is my solution:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" ControlToValidate="textbox1" runat="server"
ErrorMessage="enter text"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" ControlToValidate="textbox2" runat="server"
ErrorMessage="enter text for 2"></asp:RequiredFieldValidator>
<asp:CheckBox ID="check1" runat="server" Text="choose" />
<asp:Button ID="submitBtn" runat="server" OnClick="submitBtn_Click" Text="submit" />
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:ValidationSummary ID="summary" runat="server" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
req1.Enabled = false;
req2.Enabled = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
Response.Write("valid form");
}
else
{
Response.Write("invalid form");
}
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (check1.Checked)
{
req1.Enabled = true;
req1.Validate();
}
}

The solution for me would be to use a CustomValidator with a OnServerValidate method.
In the OnServerValidate method I would check if the checkbox is checked, in that case I would verify if the textboxes are filled. It is not necessary to do any change in the CausesValidation property.
The only condition is not to include the property "ControlToValidate". A CustomValidator does not fire if the textbox is empty that's why.
So the code would be like this:
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="prueba" />
<asp:CheckBox ID="chb" runat="server" Text="Check" />
<asp:TextBox ID="txbBox" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:Button ID="btn" runat="server" Text="Prueba" />
And the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Page.Validate();
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (chb.Checked)
{
if (txbBox.Text == String.Empty)
{
cvBox.IsValid = false;
}
}
}

Related

How to get Reference to the label in repeater item in code behind

<asp:repeater id="rpt" run="server">
<ItemTemplate>
<asp:LinkButton id="Delete" runat="server" OnCommand="Delete_Command"></asp:linkButton>
<asp:label id="lblMessage" run="server">
</ItemTemplate>
</asp:repeater>
Code Behind:
protected void Delete_Command(object sender, CommandEventArgument e)
{
}
how i get the reference to the "lblMessage" in Delete_Command.
Try this:
protected void Delete_Command(object sender, CommandEventArgs e)
{
LinkButton button = (LinkButton)sender;
Label label = (Label)button.NamingContainer.FindControl("lblMessage");
// do something with the label
}
If you:
Have bound the repeater
Have ViewState enabled
Do not re-bind the repeater earlier in the post back
this should work. If not, please verify that the id of the label is indeed exactly the same as in the ...FindControl("lblMessage");. Also make sure that runat="server" is set on all the controls involved.
Edit: One more thing to check: Search the markup file (the .aspx file) and check if there are any other controls that also use the same event in the code behind. If another control is using the same event handler and that control is not in the repeater, the label will not be found.
means are you want find a lable in Delete_Command event?
in aspx
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:LinkButton ID="Delete" runat="server" OnCommand="Delete_Command"></asp:LinkButton>
<asp:Label ID="lblMessage" run="server">
</ItemTemplate>
</asp:Repeater>
in aspx.cs
protected void Delete_Command(object sender, CommandEventArgs e)
{
foreach (RepeaterItem item in rpt.Items)
{
Label lblMessage = item.FindControl("lblMessage") as Label;
if (lblMessage != null)
{
lblMessage.Text = "";
}
}
}
If You want to make it in your way use following code in
protected void Repeater1_ItemCommand(object source, CommandEventArgs e)
{
(((LinkButton)source).NamingContainer).FindControl("lblName")
}
Another approach.. But something that you can buy
aspx
<asp:Repeater ID="Repeater1" runat="server"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%=Eval("Name") %>' ></asp:Label>
<asp:LinkButton runat="server" CommandName="Delete_Command" Text="sd"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
.cs
protected void Delete_Command(object sender, CommandEventArgument e)
{
if(e.CommandName != null)// Conditional Check
{
Label label = e.Item.FindControl("lblMessage");
// do something with the label
}
}

ASP.NET Textbox AutoPostBack Not Firing

After searching I've found a number of suggestions, but none of them are fixing the issue.
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text=""></asp:TextBox>
In the properties window, EnableViewState = True for the TextBox (Suggested here). I am typing a new value into the TextBox and then hitting the Tab key. Nothing happens nor does the break point at if(IsPostBack...) break.
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && uid.Text != "" && pw.Text == "")
{
Do stuff
}
}
UPDATE: Other TextBox setups I've tried:
<asp:TextBox runat="server" ID="uid" Text="" AutoPostBack="True" OnTextChanged="UidTextChanged"></asp:TextBox>
protected void UidTextChanged(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('it works');", true);
}
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');" OnTextChanged="UidTextChanged"></asp:TextBox>
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');"></asp:TextBox>
Whenever AutoPostBack is set to true, I receive the following error in the browser console:
"Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function
__doPostBack
(anonymous function)"
When I have the onblur property set, I receive the exact same error except instead of anonymous function it says onblur.
You could add a javascript event to the onblur for it. onblur='__doPostBack('','');'
That would cause your text box to cause a postback once it is tabbed out of.
Edit: It should be " not ' <asp:TextBox ID="TextBox1" runat="server" onblur="__doPostBack('','');" /> Just tried that and it works. Try removing the AutoPostBack="True"
Edit 2: Base on your pastebin....
<asp:Button runat="server" UseSubmitBehavior="True" ID="submit" Text="Save"
onclick="SubmitClick"/>
You can't have an ID of "submit". Change that to "btnSubmit" and the Javascript solution will work and I bet the Auopostback solution will too.
http://www.xpertdeveloper.com/2012/05/property-submit-of-object-is-not-a-function/ will explain the problem.
You can add OnTextChanged="TextBox1_TextChanged" on your textBox
Nota : It's important to set event fire, no just AutoPostBack="true".
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Code Behind:
protected void TextBox1_TextChanged(object sender, System.EventArgs e) {
.....
}

Should this be a bug or not - ASP.NET Request parameter

I posted a number of bugs on Microsoft site and while they were real bugs, MSFT will close it as design [And I figured most people favour MSFT anyways]. Here is one that I am sure they will clasify as by design but to me this is a serious bug.
This is all I have in ASPX page (NET 3.5).
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /><br />
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{ /* this works */
if (IsPostBack)
{
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
}
protected void Button1_Click(object sender, EventArgs e)
{ /* this does not */
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
Now if you include another simple HTML textbox (Not ASP) like this
<input type="text" id="mytextbox" name="mytextbox" /> // still it below the existing one
txt = Request.Params["mytextbox"]; // change to this line instead of TextBox1
Then it works in both places.
protected void Button1_Click(object sender, EventArgs e)
{ /* Now this works which is weird but it does */
If(IsPostback)
{
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
}
I therefore should close the question.
If you are forced to use the Request object instead normal asp:* controls, use it like this:
txt = Request["TextBox1"];
It will check all the HttpRequest collections.
The QueryString, Form, Cookies, or ServerVariables collection member
specified in the key parameter. If the specified key is not found,
then null is returned.
That is really fundamental stuff you're doing in that example, so I highly doubt it's a bug. From the example, it looks like you're going against the grain:
Markup
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:TextBox ID="TextBox2" runat="server" />
<asp:TextBox ID="TextBox3" runat="server" />
<asp:TextBox ID="TextBox4" runat="server" />
...
</asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /><br />
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
Code-behind
protected void Button1_Click(object sender, EventArgs e)
{
foreach (TextBox txtCtrl in PlaceHolder1.Controls.OfType<TextBox>())
{
//append the textbox value to the label
lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<TextBox> txtList = PlaceHolder1.Controls.OfType<TextBox>().ToList();
for (int ctrlIndex = 0; ctrlIndex < txtList.Count; ctrlIndex++)
{
TextBox txtCtrl = txtList.ElementAt(ctrlIndex);
if (txtCtrl != null)
{
lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
}
}
}

CustomValidator not executing on second step of a multi-panel Page

I am experiencing a problem with an ASPX page not executing a CustomValidator. The Page consists of 3 ASP Panels which swap visibility for each step in a 3 step process. The first step/panel functions as expected, executing all CustomValidators when I click the submit button. If valid, the button click hides its panel and shows the second panel for step #2 which contains another CustomValidator. When clicking the submit button on this second panel, the CustomValidator never executes and the Page always reports that it IsValid.
I have reproduced this behavior in a small, example app. Here is the relevant code...
Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:Panel ID="Panel1" runat="server" Visible="true">
<div>
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBox1"
ValidateEmptyText="true"
Display="Dynamic"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="Type in anything:" AssociatedControlID="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" />
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Show Panel #2" OnClick="Button1_Click" />
</div>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" Visible="false">
<div>
<asp:CustomValidator
ID="CustomValidator2"
runat="server"
Display="Dynamic"
OnServerValidate="CustomValidator2_ServerValidate">
</asp:CustomValidator>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="I should cause an Exception..." OnClick="Button2_Click" />
</div>
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" Visible="false">
<p>An exception should have been thrown. :(</p>
</asp:Panel>
</asp:Content>
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = true;
Panel2.Visible = false;
Panel3.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
string userEnteredText = TextBox1.Text;
if (string.IsNullOrEmpty(userEnteredText))
{
CustomValidator1.Text = "Text is required!";
args.IsValid = false;
}
else if (!userEnteredText.ToLower().Equals("anything"))
{
CustomValidator1.Text = "You didn't type 'anything'! ;)";
TextBox1.Text = null;
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
throw new Exception("This ServerValidate() method never triggers!");
}
}
I don't understand why the CustomValidator2 method is never executing. Can anyone explain this behaviour?
As you're not setting the ControlToValidate property in your scenario set the property ValidateWhenEmpty to true on the CustomValidator.
The CustomValidator will not be evaluated when the ControlToValidate is blank unless ValidateWhenEmpty is true.
UPDATE:
Ok this was wrong. But do you really need to set visibility of the panels in the Page_Load? You've done it already declaratively in the .aspx.
If you remove it from Page_Load, the validator works. I suppose it does not work if the validator is Visible=false or is inside a containing control that is Visible=false.
You should use ValidationGroup property of the buttons and the corresponding validation controls in each panel.

UpdatePanel with ASP.NET Repeater and Checkbox Aync Postback issue

I have a rather annoying issue here
I can't get my CheckBox CheckedChange event to fire, or catch or whatever it is that fails:
ASPX Code
<asp:UpdatePanel runat="server" ID="udp_Lists" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="rep_showings" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="div_assignment">
<div class="div_assignment_text">
<asp:LinkButton runat="server" ID="lnk_show_task" OnClick="lnk_show_task_Click" CommandArgument='<%# Eval("Id") %>' Text='<%# Eval("TaskTitle") %>'></asp:LinkButton>
</div>
<div class="div_assignment_checkbox">
<asp:CheckBox runat="server" ID="chk_handle" AutoPostBack="true" OnCheckedChanged="chk_handle_Changed" ToolTip='<%# Eval("Id") %>' />
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
</Triggers>
The Code behind function "chk_handle_Changed" is never reached.
The Linkbutten works perfectly.
I took a look at your problem. I used the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.rep_showings.DataSource = new object[] { new { Title = "title", ID = "id" } };
this.rep_showings.DataBind();
}
}
protected void chk_handle_Changed(object source, EventArgs e)
{
Trace.Write("here");
}
protected void lnk_show_task_Click(object source, EventArgs e)
{
Trace.Write("here 2");
}
protected void rep_showings_ItemCommand(object source, RepeaterCommandEventArgs e)
{ }
The above code works. I think you are probably re-binding your repeater on every postback - I tested this by removing the "if (!IsPostBack)" statement in Page_Load(), and I was able to reproduce the problematic behaviour you describe.
Rebinding a control on every postback should be avoided if possible. Once a control is populated, it's data is taken care of by ViewState, so unless the data is changing, you should probably not be rebinding it all the time.

Resources