CustomValidator not being called - asp.net

I have a CustomValidator that is being used to check username availability, but it isn't getting called (I also checked it with a breakpoint).
<asp:CustomValidator ID="usernameC" runat="server" ErrorMessage="Username is already taken" ControlToValidate="txtUsername" Display="None" OnServerValidate="usernameC_ServerValidate" />
Code-behind
protected void usernameC_ServerValidate(object source, ServerValidateEventArgs args)
{
if (new UsersBL().SearchUserByUsername(args.Value) == null)
args.IsValid = true;
else
args.IsValid = false;
}
What may be the problem?

it will be called when the page is being posted to the server. e.g. you have an asp:button and when the user click it the page is sent to the server and before it calls the button_click event it calls the server validation function.

Related

Viewstate expires after some time for application page in SharePoint 2013?

I have a simple ASP application page added in a SharePoint project just for presentation purposes, so it's ASP web forms page is hosted in SharePoint.
HTML:
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<asp:Label runat="server">Number 1:</asp:Label>
<asp:TextBox ID="num1" runat="server"></asp:TextBox>
<asp:Label runat="server">Number 2:</asp:Label>
<asp:TextBox ID="num2" runat="server"></asp:TextBox>
<asp:Label runat="server">Result:</asp:Label>
<asp:TextBox ID="res" runat="server"></asp:TextBox>
<asp:Button Text="ADD Numbers" runat="server" OnClick="Unnamed_Click" />
<asp:ListBox runat="server" ID="list" />
<asp:Label runat="server" ID="previousListValue"></asp:Label>
<asp:Label runat="server">Exception:</asp:Label>
<asp:TextBox ID="exception" runat="server"></asp:TextBox>
</asp:Content>
Here is code behind:
public partial class Default : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
list.DataSource = new List<ListItem>() {
new ListItem("value1", "1"),
new ListItem("value2", "2"),
new ListItem("value3", "3"),
};
list.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
try
{
res.Text = Convert.ToString(int.Parse(num1.Text) + int.Parse(num2.Text));
previousListValue.Text = "Previous list selected value is: " + list.SelectedItem.Value;
exception.Text = string.Empty;
}
catch (Exception ex)
{
exception.Text = ex.GetType().ToString() + "\t" + ex.Message;
}
}
}
When you click "ADD Numbers" button and addition of num1 and num2 textboxes is appended to the res textbox and selected value of ListBox is shown in label next to it. This works flawlessly if correct values are entered for a number and an item is selected in ListBox.
If the page is left (not interacted with) for about 10-15 minutes and "ADD Numbers" button is clicked, NullReferenceException will be thrown for list.SelectedItem.Value and also textBoxes will be empty. What happened is that the application is in postBack state(Page.IsPostBack is true) but viewstate is not restored.
I guess this has something to do with ViewState being moved to distributed cache as of version 2013 but can someone clarify this for me, and suggest me the most effective way to go about this, without changing AppFabric configuration, because 10-15 minutes of ViewState perversion is not acceptable.
As the ViewState is saved in the user's session, it is possible for
ViewState to expire if a page is not posted back within the session
expiration time.
You can configure your session timeout in web.config file (Session timeout in ASP.NET):
<sessionState timeout="60" />
(Where 50 and 60 are minutes)
You can also check if your session expired using this sample code in Master Page's Page_Load method:
if (Session.Contents.Count == 0)
{
//Session dead!
}
else
{
//Session alive!
}
Or save the logged user and test if it's null:
if (Session["userId"] == null)
{
//Session dead!
}
else
{
//Session alive!
}

ASP.NET Forms CustomCustomvalidator - always correct value

I've created simple page in ASP.NET Forms and I need to use CustomValidator control. Here's the code:
Page.aspx
<asp:ListBox
ID="listControl" runat="server"
ClientIDMode="Static"
onchange="toggleButton(this, document.getElementById('remove'))" />
<asp:CustomValidator
ID="fmValidator"
ControlToValidate="listControl"
CssClass="IncorrectResult"
runat="server"
ValidateEmptyText="True"
ErrorMessage="..."
Text="..."
OnServerValidate="Validator_OnServerValidate" />
Page.aspx.cs
protected void Validator_OnServerValidate(object source, ServerValidateEventArgs args)
{
if(isAdmin)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
The point is that I can catch an event in Validator_OnServerValidate with proper data but whatever I put in args.IsValid (I mean true or false) it always returns correct value - on the webpage everything is correct. What is wrong?
That was because page didn't reload on validating. All I had to do was enable client side validation.

ASP.Net Custom Validator failed ,form gets submitted

I have made a form in which there are two RAD DateTimePicker Controls . One is for Start-DateTime and other is for End Date Time. Inside Custom Validator, I have Compared the Date Time Picked So far and hence made it valid or invalid accordingly its Server Validate event code goes like this.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Its Design Code goes like this.
<telerik:RadDateTimePicker ID="rdpStartDate" runat="server" AutoPostBackControl="Both" onselecteddatechanged="rdpStartDate_SelectedDateChanged">
<TimeView CellSpacing="-1" Culture="en-IN">
</TimeView>
<TimePopupButton HoverImageUrl="" ImageUrl="" />
<Calendar UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False" ViewSelectorText="x">
</Calendar>
<DateInput AutoPostBack="True" DateFormat="dd-MM-yyyy" DisplayDateFormat="dd-MM-yyyy">
</DateInput>
<DatePopupButton HoverImageUrl="" ImageUrl="" />
</telerik:RadDateTimePicker>
<asp:Label ID="Label2" runat="server" Text=" To" CssClass="h_text"></asp:Label>
<telerik:RadDateTimePicker ID="rdpEndDate" runat="server" onselecteddatechanged="rdpEndDate_SelectedDateChanged" AutoPostBackControl="Both">
<TimeView CellSpacing="-1" Culture="en-IN"></TimeView>
<TimePopupButton ImageUrl="" HoverImageUrl=""></TimePopupButton>
<Calendar UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="x"></Calendar>
<DateInput DisplayDateFormat="dd-MM-yyyy" DateFormat="dd-MM-yyyy" AutoPostBack="True"></DateInput>
<DatePopupButton ImageUrl="" HoverImageUrl=""></DatePopupButton>
</telerik:RadDateTimePicker>
Validator Source Code in designer is like this.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
OnServerValidate="CustomValidator1_ServerValidate" SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
I want to ask that even when custom validator fails, My form gets submitted with faulty values. What can be the reason? How can I avoid that?
With Server validator Event like:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
You have to check on your server event as well like:(For example if you are using your validator with button click then)
protected void btn_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Write("Page is valid.");
}
else
{
Response.Write("Page is not valid!");
}
}
My suggestion: Telerik has a good client side support as well so I suggest you to use client side validation of custom validator.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
ClientValidationFunction="CheckDates"
SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
then in Javascript:
function CheckDates(sender, args)
{
var cltRdpEndDate= $find("<%=rdpEndDate.ClientID %>");
var cltRdpStartDate= $find("<%=rdpStartDate.ClientID %>");
if(cltRdpEndDate.get_dateInput().get_selectedDate()< cltRdpStartDate.get_dateInput().get_selectedDate())//if your condtion fails here
{
args.IsValid = false;
return;
}
args.IsValid = true;
}

How i can call JavaScript function from asp.net server side if script in user control

I have a ASP.NET page with 1 user controls registered.
i have one server control
<asp:LinkButton ID="vidoUpdatebtn" OnClick="vidoUpdatebtn_Click" runat="server">LinkButton</asp:LinkButton>
in .cs i handle
protected void vidoUpdatebtn_Click(object sender, EventArgs e)
{
//do something
ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "doSomeThing()", true);
}
in user control i have function doSomeThing()
function doSomeThing() {
alert("TestReady");
}
when i click on LinckButon registred function dosen't work
Write this in PageLoad (the only modifications from what you were writing are the moment in time of the registration -- PageLoad not Click, Click is too late and the face that you must write the actual implementation of the javascript function here):
protected void Page_Load(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript",
#"function doSomeThing() {
alert(""TestReady"");
}"
, true);
}
and this in the asp:LinkButton tag (you must specify the OnClientClick attribute):
<asp:LinkButton ID="vidoUpdatebtn" runat="server" OnClick="vidoUpdatebtn_Click" OnClientClick="doSomeThing()" >LinkButton</asp:LinkButton>
And it should work.
Have you tried this way:
Add Script manager on your aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Codebehind:
Page.ClientScript.RegisterStartupScript(this.GetType(),"myscript", "doSomeThing()",true);
If you want client side code to run on the button click, you could use the OnClickClick property instead of the OnClick event. That'll also avoid the need for a postback and will give immediate feedback to the user.
e.g.
<asp:LinkButton ID="vidoUpdatebtn" OnClientClick="alert('TestReady'); return false;" runat="server">LinkButton</asp:LinkButton>

ASP.Net: Ajax registration question

I worked with: ASP.Net: Ajax check for registration as a user?
It has a few errors, I don't understand:
1) It worked only one time for one textbox. If the textbox is edited a second time, the breakpoint will not be hited. Why?
2) For my Email, I have a check, that there is no duplicate, when there is one, there should the set an error panel visible, but it don't show.
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
}
When the update mode is conditional
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional"> // here the updatemode is conditional ...
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
You need to call
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
up1.Update(); // call to update the update panel "up1"
}
Sorry I'm a bit rusty, it's a while since I've used update panels.
After an update panel updates you must reinitialise the javascript on the html elements inside it.
So, to the end of your method you could add:
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
// Re-init javascript
ScriptManager.RegisterStartupScript(Type, String, "add onchange js here", Boolean);
}
see http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

Resources