UserControl conditional validation approach? - asp.net

I have a custom UserControl which contains several TextBoxes with Validators. One TextBox with corresponding Validator is optional based on a CheckBox. Pseudo:
My Control.ascx:
<asp:TextBox id="txtAddress" />
<asp:Validator id="valAddress" />
<asp:CheckBox id="condition" />
<asp:TextBox id="txtConditional" />
<asp:Validator id="valConditional" ValidationGroup="ConditionalGroup" />
My Control.ascx.cs
public void Validate() {
if(condition.Checked) {
Page.Validate("ConditionalGroup");
}
}
I also have a page which basically looks like this:
Page.aspx
<my:Control id="myControl" />
<asp:Button onClick="doPost" />
Page.aspx.cs
protected void doPost(object sender, EventArgs e) {
myControl.Validate(); //This feels wrong
if(Page.IsValid) {
//go
}
}
This all works, however I would like to take the myControl.Validate() line out of the Page.aspx.cs and put it in the My Control.ascx.cs. Putting it in the Page_Load of the control is not an option because the conditional checkbox value is always false. There is no event available after Page_Load and before the doPost click handler is fired...
It feels wrong to call the custom Validate function on the Page where I think it should belong somewhere in the UserControl. Is it true that this is architecturally wrong? Is there another solution for this maybe by using an event handler?

You could try by enabling the validator only if the user checks on the check box. And disable the validator if the unchecks it. This has to be done in the user control. It can be done in the client side or in the server side. In this way, the page would validate all the validators that are enabled for the page.

Related

runat server field not filled when clicking on button?

I'm using an aspx file as my main page with the following code snippet:
<input type="text" runat="server" id="Password" />
<asp:Button runat="server" id="SavePassword"
Text="Save" OnClick="SavePassword_Click"/>
Then in the code behind I use:
protected void SavePassword_Click(object sender, EventArgs e)
{
string a = Password.Value.ToString();
}
Setting Password.Value in the Page_Load works as expected, but setting a to the value results in an empty string in a regardless what I type in on the page befoere I click the save button.
Am I overlooking here something?
You should add label field with name labelShow in aspx page like this
<asp:Label ID="labelShow" runat="server"></asp:Label>
Then add the string into .cs file
protected void SavePassword_Click(object sender, EventArgs e)
{
string a = Password.Value.ToString();
labelShow.Text = a.ToString();
}
I can figure several errors :
You say something about Page_Load. You should always remember Page_Load is executed at every postback. So if you write something into the textbox at Page_Load, it will erase the value typed by user. You can change this behavior by veriyfing
if(!IsPostBack)
{
// Your code
}
around your Page_Load content.
input runat="server" is not the proper way to do TextBox in ASP.Net, in most cases you should use asp:TextBox
You don't do anything with your "a" string, your current code sample does nothing, whether the Password field is properly posted or not. You can do as suggested by Ravi in his answer to display it.
I suggest you to to learn how to use VS debugger, and to read a good course on ASP.Net Webforms to learn it.

Form data is saving and validation message is also displaying

We are using the callbackpanel for the validation of the Devexpress controls but what actually happening is :
If we click submit button without entering any thing in textboxes in the form. It is showing the validation messages but it is also saving the blank data to the database.
I want to know if validation message is showing then why event in backend is calling for saving data ?
Basically in DevExpress ASPxCallbackPanel, a Button Click does not trigger a Callback, it triggers a Postback that is the difference between an UpdatePanel and a CallbackPanel.
So you have to call the ASPxCallbackPanelClient.PerformCallback('PARAM'); instead.
You did not mention how you trigger the callback, you did not show how your ASPxButton code looks or how your ASPxCallbackPanel looks or how your Validator looks, so considering that please see code below that works very well in you scenario
All the controls as DX, including validators and buttons
<dx:ASPxCallbackPanel runat="server" ID="cbpDIActions" ClientInstanceName="cbpDIActions" OnCallback="cbpDIActions_Callback">
<panelcollection>
<dx:PanelContent>
<dx:ASPxSpinEdit ID="txtBuilFixtNoBathrooms" runat="server" ValidationSettings-RequiredField-IsRequired="true" ValidationSettings-ValidationGroup="SubmitValidation">
</dx:ASPxSpinEdit>
<dx:ASPxButton ID="btn" runat="server" AutoPostBack="false" Text="Process" UseSubmitBehavior="False"
ValidationSettings-ValidationGroup="SubmitValidation" CausesValidation="true"
>
<ClientSideEvents Click="function(s,e){
ASPxClientEdit.ValidateGroup('SubmitValidation');
if (ASPxClientEdit.AreEditorsValid()) {
if(!cbpDIActions.InCallback()) {
cbpDIActions.PerformCallback('PARAM');}
}
}" />
</dx:ASPxButton>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
And in the backend you put all your code in the callback event
protected void cbpDIActions_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
{
if (e.Parameter != null && e.Parameter.ToString() == "PARAM")
{
//PROCESS YOUR CODE
}
}

Why aren't all controls initialised at the event handling point of the ASP.NET page lifecycle?

I have a user control embedded in a web part. It has the following snippets of code:
protected TextBox searchTextBox;
protected Button goButton;
protected Button nextButton;
protected Repeater pushpins;
protected Label currentPageLabel;
protected void goButton_Click(object sender, EventArgs e)
{
// Do stuff
}
<asp:TextBox ID="searchTextBox" runat="server" />
<asp:Button ID="goButton" runat="server" Text="Go" OnClick="goButton_Click" />
<asp:Repeater ID="pushpins" runat="server" EnableViewState="false">
<ItemTemplate>Blah</ItemTemplate>
</asp:Repeater>
<asp:Label ID="currentPageLabel" runat="server" />
<asp:Button ID="nextButton" runat="server" Text=" >> " OnClick="nextButton_Click" />
(There is no OnLoad or CreateChildControls method.)
If I place a breakpoint on the first line of goButton_Click, I find:
searchTextBox: initialised
goButton: initialised
nextButton: NULL
pushpins: initialised
currentPageLabel: NULL
Why are some controls initialised and others not? How do I get around this if I'd like to update the Text property on currentPageLabel?
Update:
I've placed breakpoints all the way through the page life cycle and found that nextButton and currentPageLabel are never initialised. The breakpoints were placed at OnLoad, CreateChildControls, goButton_Click, OnPreRender, Render and OnUnload.
Is it possible you've inadvertently got local variables named currentPageLabel and/or nextButton declared somewhere? The compiler will happily allow this...
This is especially common in a move from ASP.NET 1.1 to 2.0 or higher, since the way the designer defined these controls changed.
The problem was that all of the controls that weren't being initialised were inside a HeaderTemplate within a Repeater control. (To save space I didn't paste all of my code into the question, dang it.)
I moved them out and the problem is resolved. Obviously controls in the HeaderTemplate are instantiated by the Repeater and do not follow the normal page life cycle.

Why is break point unreachable when using jQuery Droplistfilter

I am using this drop list filter on my Asp.Net Form.
jQuery plugin DropListFilter
The filter on the dropdownlist list works perfecty.
<script type="text/javascript">
$(document).ready(function() {
$('select').droplistFilter();
});
</script>
<asp:DropDownList ID="ddlMonth" runat="server" CssClass="ddlStyle"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv_ddlMonth" runat="server" ControlToValidate="ddlMonth"
CssClass="warning" Display="Dynamic" ErrorMessage="*" ForeColor=""></asp:RequiredFieldValidator>
<asp:Button ID="btnRun" runat="server" CssClass="btnStyle" OnClick="btnRun_Click" Text="Run Report" />
CodeBehind
protected void btnRun_Click(object sender, EventArgs e)
{
Response.Write(ddlMonth.SelectedValue.ToString());
return;
}
If I do a search on the dropdownlist using the jQuery filter and click run report, the debugger does not stop at the above Response.Write statement.
On application of the filter and pressing Run the debugger does not even hit the load method below.
protected void Page_Load(object sender, EventArgs e)
{
// Bind Month if !PostBack
}
Upon further investigating I am getting the following error on the Application_Error:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I do not want to disable the event validation, so what can I do to make the filter work?
The droplistFilter is changing what is being expected by ASP.
ASP doesn't like it when things are changed without it's explicit written consent.
ASP is expecting that dropdown to contain what it put in the dropdown, when you change what is in that with javascript asp sees that as a security risk and is giving you the validation error.

OnClick vs OnClientClick for an asp:CheckBox?

Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
and this doesn't (no error):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
but this works:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged
I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
You can do the tag like this:
<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />
The .checked property in the called JavaScript will be correct...the current state of the checkbox:
function checkchanged(obj) {
alert(obj.checked)
}
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);

Resources