天天看点

Sample Code on ASP.NET Validation in Depth

Base on my previous post "ASP.NET Validation in Depth" http://blog.csdn.net/riverlau/article/details/7021297, I have wrote the sample code to show how to do the validation between parent page control and user control, which valid parent page control value should equals to the user control. 

The custom validator is hosted in user control side And it handles both server side and client side validation

Result View

Sample Code on ASP.NET Validation in Depth

User Control

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="UserControlValidation.WebUserControl1" %>
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem>Dept1</asp:ListItem>
    <asp:ListItem>Dept2</asp:ListItem>
    <asp:ListItem>Dept3</asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator 
ID="CustomValidator1" 
runat="server" 
ControlToValidate="DropDownList1"
ErrorMessage="CustomValidator" 
    onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
           
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserControlValidation
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        private bool isValid;

        public bool IsValid
        {
            get { return isValid; }
            set 
            { 
                isValid = value; 
            }
        }

        public string SelectedValue 
        {
            get
            {
                return DropDownList1.SelectedItem.Text;
            }
        
        }

        public CustomValidator ucCustomValidator
        {
            get
            {
                return this.CustomValidator1;
            }
        }

        public DropDownList ucDropDownList
        {
            get
            {
                return this.DropDownList1;
            }
        }
        

        protected void Page_Load(object sender, EventArgs e)
        {
            IsValid = false;
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = isValid;
        }
    }
}
           

Page Control

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="UserControlValidation._Default" %>

<%@ Register Src="~/WebUserControl1.ascx" TagName="MessageControl" TagPrefix="ucMsg" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" target="_blank" rel="external nofollow"  title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409" target="_blank" rel="external nofollow" 
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID">
            </asp:BoundField>
            <asp:BoundField HeaderText="Name" 
                 DataField="Name" 
                 ></asp:BoundField>
            <asp:TemplateField>
                 <ItemTemplate>
                    <asp:Label ID="lblDept" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Dept")%>'>
                        
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <HeaderTemplate>
                    Dept
                </HeaderTemplate>
                <ItemTemplate>
                   <ucMsg:MessageControl ID="MessageControl1" runat="Server"></ucMsg:MessageControl>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" Text="Button" οnclick="Button1_Click" CausesValidation="false" />
</asp:Content>
           
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserControlValidation
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<TestData> test = new List<TestData>();
                for (int i = 0; i < 10; i++)
                {
                    TestData t = new TestData(i.ToString(), "Name" + i, "Dept" + i);
                    test.Add(t);
                }
                GridView1.DataSource = test;
                GridView1.DataBind();
            }

            foreach (GridViewRow r in GridView1.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    #region validation
                    WebUserControl1 uc = r.FindControl("MessageControl1") as WebUserControl1;
                    Label lblText = r.FindControl("lblDept") as Label;

                    string functionName = "validate_" + uc.ucDropDownList.ClientID;
                    string script = String.Format("function {0}(source, args){{args.IsValid = false; var lbl=$('#{2}').text() ;var text = $('#{1} option:selected').text();if (text==lbl) {{args.IsValid = true;}} else {{ args.IsValid = false}} }}", functionName, uc.ucDropDownList.ClientID, lblText.ClientID);
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), functionName + "_script", script, true);
                    //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), functionName + "_script", script, true);
                    uc.ucCustomValidator.ClientValidationFunction = functionName;
                    #endregion
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow r in GridView1.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    WebUserControl1 uc = r.FindControl("MessageControl1") as WebUserControl1;
                    Label lblText = r.FindControl("lblDept") as Label;

                    if (String.Compare(lblText.Text,uc.SelectedValue)==0)
                    {
                        uc.IsValid = true;
                    }
                }
            }

            //Call Validation
            Page.Validate();
            if (Page.IsValid)
            {
                Response.Write("Hi!");
            }
            else
            {
                Response.Write("No Hi!");
            }
        }
    }

    public class TestData
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Dept { get; set; }

        public TestData(string id, string name, string dept)
        {
            ID = id;
            Name = name;
            Dept = dept;
        }
    }
}