Wrox Programmer Forums
|
ASP.NET 4.5.1 General Discussion For ASP.NET 4.5.1 discussions not relating to a specific Wrox book
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 4.5.1 General Discussion section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old January 13th, 2015, 03:23 AM
Registered User
 
Join Date: Jun 2014
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default CustomValidator Server-Side Not Firing

I'm trying to make a very basic mailing list control, but i'm having trouble with my CustomValidators. I've been working on the unsubscribe side of it, and I want to check to see if the email trying to be unsubscribed is actually on the mailing list, and inversely for subscribing. But I can't seem to get my server side validation functions to fire. I have breakpoints at the start of each validation function, and they are never triggered. For testing, I immediately set args.IsValid = false;

Hopefully one of you can help me out with this. Inbound wall of code.

MailingListControl.ascx
Code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MailingListControl.ascx.cs" Inherits="Controls_MailingList" %>

<h2><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></h2>
<asp:Panel ID="MailingListContainer" runat="server" CssClass="ControlContainer">
    <asp:GridView ID="Display" runat="server" Visible="false"></asp:GridView>
    <asp:Panel ID="Subscribe" runat="server" Visible="false">
        <table>
            <tr>
                <td>First Name:</td>
                <td>
                    <asp:TextBox ID="FirstNameTB" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="FirstNameTB" CssClass="ErrorMessage" ErrorMessage="Enter your first name" Display="Dynamic" ValidationGroup="Subscribe">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td>
                    <asp:TextBox ID="LastNameTB" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="LastNameTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your last name" ValidationGroup="Subscribe">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>Email:</td>
                <td>
                    <asp:TextBox ID="EmailTB" runat="server" TextMode="Email"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="EmailTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your email address" ValidationGroup="Subscribe">*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="EmailTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Please enter a valid email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="Subscribe">*</asp:RegularExpressionValidator>
                    <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="EmailTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="That email is already subscribed" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="Subscribe">*</asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>Artist:</td>
                <td>
                    <asp:CheckBox ID="ArtistCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Programmer:</td>
                <td>
                    <asp:CheckBox ID="ProgrammerCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Sound:</td>
                <td>
                    <asp:CheckBox ID="SoundCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Story:</td>
                <td>
                    <asp:CheckBox ID="StoryCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="SubmitSubscribe" runat="server" Text="Submit" OnClick="SubmitSubscribe_Click" ValidationGroup="Subscribe" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="ErrorMessage" HeaderText="Please correct the following errors:" ValidationGroup="Subscribe" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    <asp:Panel ID="Unsubscribe" runat="server" Visible="false">
        <table>
            <tr>
                <td>Email:</td>
                <td>
                    <asp:TextBox ID="EmailUnsubTB" runat="server" TextMode="Email"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="EmailUnsubTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your email address" ValidationGroup="Unsubscribe">*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="EmailUnsubTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Please enter a valid email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="Unsubscribe">*</asp:RegularExpressionValidator>
                    <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="EmailUnsubTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="That email is already unsubscribed" OnServerValidate="CustomValidator2_ServerValidate" ValidationGroup="Unsubscribe">*</asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="SubmitUnsubscribe" runat="server" Text="Submit" OnClick="SubmitUnsubscribe_Click" ValidationGroup="Unsubscribe" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:ValidationSummary ID="ValidationSummary2" runat="server" CssClass="ErrorMessage" HeaderText="Please correct the following errors:" ValidationGroup="Unsubscribe" />
                </td>
            </tr>
        </table>
    </asp:Panel>
</asp:Panel>

MailingListControl.ascx.cs
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Controls_MailingList : System.Web.UI.UserControl
{
    public string Use { get; set; }

    public string CsvPath { get; set; }

    public class User
    {
        public string First { get; set; }
        public string Last { get; set; }
        public string Email { get; set; }
        public bool Programmer { get; set; }
        public bool Artist { get; set; }
        public bool Story { get; set; }
        public bool Sound { get; set; }

        public User(string first, string last, string email, bool programmer, bool artist, bool story, bool sound)
        {
            First = first;
            Last = last;
            Email = email;
            Programmer = programmer;
            Artist = artist;
            Story = story;
            Sound = sound;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            Label1.Text = "Mailing List Action Complete.";
            Display.Visible = false;
            Unsubscribe.Visible = false;
            Subscribe.Visible = false;
        }

        //else if (Use == "Display")
        else if (Use == "ShowMailingList")
        {
            Display.Visible = true;
            Label1.Text = "Viewing Mailing List.";

            List<User> users = ReadCsv(CsvPath);

            IEnumerable<User> SortedUsers =
                from user in users
                orderby user.Last
                select user;

            Display.DataSource = SortedUsers;
            Display.DataBind();
        }

        else if (Use == "Unsubscribe")
        {
            Unsubscribe.Visible = true;
            Label1.Text = "Unsubscribing from Mailing List.";
        }

        else //if (Use == "Subscribe")
        {
            Subscribe.Visible = true;
            Label1.Text = "Subscribing to Mailing List.";
        }
    }

    protected List<User> ReadCsv(string Path)
    {
        String[] csv = File.ReadAllLines(Server.MapPath(Path));

        List<User> users = new List<User>();
        for (int i = 1; i < csv.Length; i++)
        {
            var fields = csv[i].Split(','); // csv delimiter
            User user = new User(fields[0], fields[1], fields[2], bool.Parse(fields[3]), bool.Parse(fields[4]), bool.Parse(fields[5]), bool.Parse(fields[6]));
            users.Add(user);
        }

        return users;
    }

    protected void WriteCsv(string Path, List<User> Users)
    {
        StreamWriter file = new StreamWriter(Server.MapPath(Path));

        var props = typeof(User).GetProperties();
        for (int i = 0; i < props.Length; i++)
        {
            if (i < props.Length - 1)
                file.Write(props[i].Name + ",");
            else
                file.Write(props[i].Name);
        }
        file.WriteLine();

        foreach (User user in Users)
        {
            for (int i = 0; i < props.Length; i++)
            {
                var propertyValue = props[i].GetValue(user, null);

                if (i < props.Length - 1)
                    file.Write(propertyValue + ",");
                else
                    file.Write(propertyValue);
            }
            file.WriteLine();
        }

        file.Close();
    }
    protected void SubmitSubscribe_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            List<User> users = ReadCsv(CsvPath);

            users.Add(new User(FirstNameTB.Text, LastNameTB.Text, EmailTB.Text, ProgrammerCB.Checked, ArtistCB.Checked, StoryCB.Checked, SoundCB.Checked));

            WriteCsv(CsvPath, users);
        }
    }

    protected void SubmitUnsubscribe_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            List<User> users = ReadCsv(CsvPath);

            IEnumerable<User> LinqUsers =
                from user in users
                where user.Email != EmailUnsubTB.Text
                select user;

            WriteCsv(CsvPath, LinqUsers.ToList());
        }
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = false;
        List<User> users = ReadCsv(CsvPath);

        IEnumerable<User> LinqUsers =
            from user in users
            where user.Email == EmailTB.Text
            select user;

        if (LinqUsers.Count() > 0)
            args.IsValid = false;
    }

    protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = false;
        List<User> users = ReadCsv(CsvPath);

        IEnumerable<User> LinqUsers =
            from user in users
            where user.Email != EmailUnsubTB.Text
            select user;

        if (LinqUsers.Count() == users.Count())
            args.IsValid = false;
    }
}
 
Old January 14th, 2015, 03:41 AM
Registered User
 
Join Date: Jun 2014
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I figured out what my problem was. In case anybody stumbles upon this, i'll give my solution.

After a night of sleep and a shower, I remembered that custom validator server function fires on the server, no duh. In order to do that, the page (or control) has to postback. In the above code, the first thing I did was to check for postback and complete the transaction. So my solution was to remove the else from the first else if in the Page_Load, which ensures that one of the panels of the control gets set to visible. Then in the submit button click functions, I hide the appropriate panel and show the appropriate message.

Anyway, here is my code if somebody wants to compare the files.

MailingListControl.ascx
Code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MailingListControl.ascx.cs" Inherits="Controls_MailingList" %>

<h2><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></h2>
<asp:Panel ID="MailingListContainer" runat="server" CssClass="ControlContainer">
    <asp:GridView ID="Display" runat="server" Visible="false"></asp:GridView>
    <asp:Panel ID="Subscribe" runat="server" Visible="false">
        <table>
            <tr>
                <td>First Name:</td>
                <td>
                    <asp:TextBox ID="FirstNameTB" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="FirstNameTB" CssClass="ErrorMessage" ErrorMessage="Enter your first name" Display="Dynamic" ValidationGroup="Subscribe">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td>
                    <asp:TextBox ID="LastNameTB" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="LastNameTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your last name" ValidationGroup="Subscribe">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>Email:</td>
                <td>
                    <asp:TextBox ID="EmailTB" runat="server" TextMode="Email"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="EmailTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your email address" ValidationGroup="Subscribe">*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="EmailTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Please enter a valid email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="Subscribe">*</asp:RegularExpressionValidator>
                    <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="EmailTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="That email is already subscribed" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="Subscribe">*</asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>Artist:</td>
                <td>
                    <asp:CheckBox ID="ArtistCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Programmer:</td>
                <td>
                    <asp:CheckBox ID="ProgrammerCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Sound:</td>
                <td>
                    <asp:CheckBox ID="SoundCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Story:</td>
                <td>
                    <asp:CheckBox ID="StoryCB" runat="server" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="SubmitSubscribe" runat="server" Text="Submit" OnClick="SubmitSubscribe_Click" ValidationGroup="Subscribe" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="ErrorMessage" HeaderText="Please correct the following errors:" ValidationGroup="Subscribe" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    <asp:Panel ID="Unsubscribe" runat="server" Visible="false">
        <table>
            <tr>
                <td>Email:</td>
                <td>
                    <asp:TextBox ID="EmailUnsubTB" runat="server" TextMode="Email"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="EmailUnsubTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your email address" ValidationGroup="Unsubscribe">*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="EmailUnsubTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Please enter a valid email address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="Unsubscribe">*</asp:RegularExpressionValidator>
                    <asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="EmailUnsubTB" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="That email is not on the mailing list" OnServerValidate="CustomValidator2_ServerValidate" ValidationGroup="Unsubscribe">*</asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="SubmitUnsubscribe" runat="server" Text="Submit" OnClick="SubmitUnsubscribe_Click" ValidationGroup="Unsubscribe" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:ValidationSummary ID="ValidationSummary2" runat="server" CssClass="ErrorMessage" HeaderText="Please correct the following errors:" ValidationGroup="Unsubscribe" />
                </td>
            </tr>
        </table>
    </asp:Panel>
</asp:Panel>

MailingListControl.ascx.cs
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Controls_MailingList : System.Web.UI.UserControl
{
    public string Use { get; set; }

    public string CsvPath { get; set; }

    public class User
    {
        public string First { get; set; }
        public string Last { get; set; }
        public string Email { get; set; }
        public bool Programmer { get; set; }
        public bool Artist { get; set; }
        public bool Story { get; set; }
        public bool Sound { get; set; }

        public User(string first, string last, string email, bool programmer, bool artist, bool story, bool sound)
        {
            First = first;
            Last = last;
            Email = email;
            Programmer = programmer;
            Artist = artist;
            Story = story;
            Sound = sound;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            Label1.Text = "Mailing List Action Complete.";
            Display.Visible = false;
            Unsubscribe.Visible = false;
            Subscribe.Visible = false;
        }

        //else if (Use == "Display")
        if (Use == "ShowMailingList")
        {
            Display.Visible = true;
            Label1.Text = "Viewing Mailing List.";

            List<User> users = ReadCsv(CsvPath);

            IEnumerable<User> SortedUsers =
                from user in users
                orderby user.Last
                select user;

            Display.DataSource = SortedUsers;
            Display.DataBind();
        }

        else if (Use == "Unsubscribe")
        {
            Unsubscribe.Visible = true;
            Label1.Text = "Unsubscribing from the Mailing List.";
        }

        else
        {
            Subscribe.Visible = true;
            Label1.Text = "Subscribing to the Mailing List.";
        }
    }

    protected List<User> ReadCsv(string Path)
    {
        String[] csv = File.ReadAllLines(Server.MapPath(Path));

        List<User> users = new List<User>();
        for (int i = 1; i < csv.Length; i++)
        {
            var fields = csv[i].Split(','); // csv delimiter
            User user = new User(fields[0], fields[1], fields[2], bool.Parse(fields[3]), bool.Parse(fields[4]), bool.Parse(fields[5]), bool.Parse(fields[6]));
            users.Add(user);
        }

        return users;
    }

    protected void WriteCsv(string Path, List<User> Users)
    {
        StreamWriter file = new StreamWriter(Server.MapPath(Path));

        var props = typeof(User).GetProperties();
        for (int i = 0; i < props.Length; i++)
        {
            if (i < props.Length - 1)
                file.Write(props[i].Name + ",");
            else
                file.Write(props[i].Name);
        }
        file.WriteLine();

        foreach (User user in Users)
        {
            for (int i = 0; i < props.Length; i++)
            {
                var propertyValue = props[i].GetValue(user, null);

                if (i < props.Length - 1)
                    file.Write(propertyValue + ",");
                else
                    file.Write(propertyValue);
            }
            file.WriteLine();
        }

        file.Close();
    }

    protected void SubmitSubscribe_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            List<User> users = ReadCsv(CsvPath);

            users.Add(new User(FirstNameTB.Text, LastNameTB.Text, EmailTB.Text, ProgrammerCB.Checked, ArtistCB.Checked, StoryCB.Checked, SoundCB.Checked));

            WriteCsv(CsvPath, users);

            Subscribe.Visible = false;
            Label1.Text = "Thanks for subscribing " + FirstNameTB.Text + " " + LastNameTB.Text + "<br />" + "Emails will be sent to " + EmailTB.Text;
        }
    }

    protected void SubmitUnsubscribe_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (Page.IsValid)
        {
            List<User> users = ReadCsv(CsvPath);

            IEnumerable<User> LinqUsers =
                from user in users
                where user.Email != EmailUnsubTB.Text
                select user;

            WriteCsv(CsvPath, LinqUsers.ToList());

            Unsubscribe.Visible = false;
            Label1.Text = "Successfully unsubscribed " + EmailUnsubTB.Text;
        }
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        List<User> users = ReadCsv(CsvPath);

        IEnumerable<User> LinqUsers =
            from user in users
            where user.Email == EmailTB.Text
            select user;

        if (LinqUsers.Count() > 0)
            args.IsValid = false;
    }

    protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        List<User> users = ReadCsv(CsvPath);

        IEnumerable<User> LinqUsers =
            from user in users
            where user.Email != EmailUnsubTB.Text
            select user;

        if (LinqUsers.Count() == users.Count())
            args.IsValid = false;
    }
}

Last edited by xxAtrain223; January 14th, 2015 at 03:42 AM.. Reason: fixed closing code tag





Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem Converting Client-side to Server-side Code kwilliams ASP.NET 2.0 Professional 1 November 21st, 2007 05:25 PM
Firing server side events at client side codes mehdi62b ASP.NET 1.0 and 1.1 Basics 6 May 18th, 2005 09:11 AM
sharing a server-side variable with client-side pigtail Javascript How-To 6 November 4th, 2004 02:01 AM
Accessing Server Side Data on Client Side steve456 Classic ASP Professional 3 October 15th, 2003 02:33 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.