首页 > 代码库 > ajax验证表单元素规范正确与否 ajax展示加载数据库数据 ajax三级联动
ajax验证表单元素规范正确与否 ajax展示加载数据库数据 ajax三级联动
一、ajax验证表单元素规范正确与否
以用ajax来验证用户名是否被占用为例
1创建表单元素<input type="text" id="t">
2在js中用keyup事件来进行操作
3创建ajax格式和内容:格式:
$.ajax({
url:"哪一个服务端处理器",
data:{"自己起名",所需要传给处理器的数据},
type:"post",
dataType:"json",
success:function(aa){
//对处理器返回的值aa进行处理操作
},
error:function(){
alert("处理器连接失败");
}
});
4.代码示范
(1)建立linq
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.17929 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq; using System.Linq.Expressions; using System.Reflection; [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="mydb")] public partial class chinaDataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region 可扩展性方法定义 partial void OnCreated(); partial void InsertChinaStates(ChinaStates instance); partial void UpdateChinaStates(ChinaStates instance); partial void DeleteChinaStates(ChinaStates instance); #endregion public chinaDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString, mappingSource) { OnCreated(); } public chinaDataContext(string connection) : base(connection, mappingSource) { OnCreated(); } public chinaDataContext(System.Data.IDbConnection connection) : base(connection, mappingSource) { OnCreated(); } public chinaDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public chinaDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public System.Data.Linq.Table<ChinaStates> ChinaStates { get { return this.GetTable<ChinaStates>(); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ChinaStates")] public partial class ChinaStates : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private string _AreaCode; private string _AreaName; private string _ParentAreaCode; private bool _Root; private short _Zone; private string _NavigateURL; #region 可扩展性方法定义 partial void onl oaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnAreaCodeChanging(string value); partial void OnAreaCodeChanged(); partial void OnAreaNameChanging(string value); partial void OnAreaNameChanged(); partial void OnParentAreaCodeChanging(string value); partial void OnParentAreaCodeChanged(); partial void OnRootChanging(bool value); partial void OnRootChanged(); partial void OnZoneChanging(short value); partial void OnZoneChanged(); partial void OnNavigateURLChanging(string value); partial void OnNavigateURLChanged(); #endregion public ChinaStates() { OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AreaCode", DbType="VarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)] public string AreaCode { get { return this._AreaCode; } set { if ((this._AreaCode != value)) { this.OnAreaCodeChanging(value); this.SendPropertyChanging(); this._AreaCode = value; this.SendPropertyChanged("AreaCode"); this.OnAreaCodeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AreaName", DbType="NVarChar(20) NOT NULL", CanBeNull=false)] public string AreaName { get { return this._AreaName; } set { if ((this._AreaName != value)) { this.OnAreaNameChanging(value); this.SendPropertyChanging(); this._AreaName = value; this.SendPropertyChanged("AreaName"); this.OnAreaNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ParentAreaCode", DbType="VarChar(20) NOT NULL", CanBeNull=false)] public string ParentAreaCode { get { return this._ParentAreaCode; } set { if ((this._ParentAreaCode != value)) { this.OnParentAreaCodeChanging(value); this.SendPropertyChanging(); this._ParentAreaCode = value; this.SendPropertyChanged("ParentAreaCode"); this.OnParentAreaCodeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Root", DbType="Bit NOT NULL")] public bool Root { get { return this._Root; } set { if ((this._Root != value)) { this.OnRootChanging(value); this.SendPropertyChanging(); this._Root = value; this.SendPropertyChanged("Root"); this.OnRootChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Zone", DbType="SmallInt NOT NULL")] public short Zone { get { return this._Zone; } set { if ((this._Zone != value)) { this.OnZoneChanging(value); this.SendPropertyChanging(); this._Zone = value; this.SendPropertyChanged("Zone"); this.OnZoneChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NavigateURL", DbType="VarChar(100)")] public string NavigateURL { get { return this._NavigateURL; } set { if ((this._NavigateURL != value)) { this.OnNavigateURLChanging(value); this.SendPropertyChanging(); this._NavigateURL = value; this.SendPropertyChanged("NavigateURL"); this.OnNavigateURLChanged(); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } #pragma warning restore 1591
(2)default页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src=http://www.mamicode.com/"js/jquery-1.7.1.min.js"></script><%--引用jquery--%> </head> <body> <form id="form1" runat="server"> <div> <input type="text" id="t" /><span id="s"></span> </div> </form> </body> </html> <script> $("#t").keyup(function () {//用keyup操作方式来验证 var a = $(this).val();//先取值 //1、将数据提交到服务端去 $.ajax({ url: "ajax/SelectUserName.ashx",//服务端处理器路径 data: { "shuju": a },//将数据a提交到服务端去,”shuju“是自己随意起名 type: "post",//规定提交方式,有post和get两种 dataType: "json",//规定返回交互的数据类型,有”json“和”xml“。但是json比xml好用 success: function (b) {//b为SelectUserName.ashx中返回的namejson的值 if (b.has == "0") { $("#s").text("恭喜,用户名能使用").css("color","blue"); } else { $("#s").text("抱歉,用户名已被使用").css("color","red"); } },//sucess error: function () {//success不成功,会走这一步!! alert("服务器连接失败"); } });//ajax });//keyup </script>
(3)服务处理器SelectUserName.ashx页面,(建立在新建文件夹ajax的里面,与default平级)
<%@ WebHandler Language="C#" Class="SelectUserName" %> using System; using System.Web; using System.Linq; public class SelectUserName : IHttpHandler { public void ProcessRequest (HttpContext context) { string name = context.Request["shuju"];//获取Default.aspx中提交的数据 string namejson = "{\"has\":\"0\"}";//建立json,格式为{"key":"value","key":"value",..........} using (xinxiDataContext cnn = new xinxiDataContext()) { var ss = cnn.Users.Where(r => r.UserName == name).AsEnumerable();//查询是否有该UserName,此处没有进行数据访问 此处需要引用using System.Linq; if (ss.Count() > 0)//如果有该UesrName,ss里面是有数据的,反之,没有 { namejson = "{\"has\":\"1\"}";//修改namejson内容 } } context.Response.Write(namejson);//将namejson返回出去 context.Response.End();//关闭输出 } public bool IsReusable { get { return false; } } }
二、ajax展示加载数据库数据
1、服务处理器的作用就是用含有json的数组把数据传出来,再在web窗体端对该数组进行处理。
含有json的数组的格式:[{"key1":"value1","key2":"value2"},{"key3":"value3"}........{"keyn":"value3"}]。
2、以数据库xinxi中Uers和Nation表为例
(1)建立linq。(xinxi.dbml)
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.17929 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq; using System.Linq.Expressions; using System.Reflection; [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="xinxi")] public partial class xinxiDataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region 可扩展性方法定义 partial void OnCreated(); partial void InsertUsers(Users instance); partial void UpdateUsers(Users instance); partial void DeleteUsers(Users instance); partial void InsertNation(Nation instance); partial void UpdateNation(Nation instance); partial void DeleteNation(Nation instance); #endregion public xinxiDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["xinxiConnectionString"].ConnectionString, mappingSource) { OnCreated(); } public xinxiDataContext(string connection) : base(connection, mappingSource) { OnCreated(); } public xinxiDataContext(System.Data.IDbConnection connection) : base(connection, mappingSource) { OnCreated(); } public xinxiDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public xinxiDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public System.Data.Linq.Table<Users> Users { get { return this.GetTable<Users>(); } } public System.Data.Linq.Table<Nation> Nation { get { return this.GetTable<Nation>(); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Users")] public partial class Users : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private string _UserName; private string _Password; private bool _Sex; private string _NickName; private System.DateTime _Birthday; private string _Nation; private string _State; private EntityRef<Nation> _Nation1; #region 可扩展性方法定义 partial void onl oaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnUserNameChanging(string value); partial void OnUserNameChanged(); partial void OnPasswordChanging(string value); partial void OnPasswordChanged(); partial void OnSexChanging(bool value); partial void OnSexChanged(); partial void OnNickNameChanging(string value); partial void OnNickNameChanged(); partial void OnBirthdayChanging(System.DateTime value); partial void OnBirthdayChanged(); partial void OnNationChanging(string value); partial void OnNationChanged(); partial void OnStateChanging(string value); partial void OnStateChanged(); #endregion public Users() { this._Nation1 = default(EntityRef<Nation>); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_UserName", DbType="NVarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)] public string UserName { get { return this._UserName; } set { if ((this._UserName != value)) { this.OnUserNameChanging(value); this.SendPropertyChanging(); this._UserName = value; this.SendPropertyChanged("UserName"); this.OnUserNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Password", DbType="NVarChar(20) NOT NULL", CanBeNull=false)] public string Password { get { return this._Password; } set { if ((this._Password != value)) { this.OnPasswordChanging(value); this.SendPropertyChanging(); this._Password = value; this.SendPropertyChanged("Password"); this.OnPasswordChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Sex", DbType="Bit NOT NULL")] public bool Sex { get { return this._Sex; } set { if ((this._Sex != value)) { this.OnSexChanging(value); this.SendPropertyChanging(); this._Sex = value; this.SendPropertyChanged("Sex"); this.OnSexChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NickName", DbType="NVarChar(20) NOT NULL", CanBeNull=false)] public string NickName { get { return this._NickName; } set { if ((this._NickName != value)) { this.OnNickNameChanging(value); this.SendPropertyChanging(); this._NickName = value; this.SendPropertyChanged("NickName"); this.OnNickNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Birthday", DbType="DateTime NOT NULL")] public System.DateTime Birthday { get { return this._Birthday; } set { if ((this._Birthday != value)) { this.OnBirthdayChanging(value); this.SendPropertyChanging(); this._Birthday = value; this.SendPropertyChanged("Birthday"); this.OnBirthdayChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Nation", DbType="NVarChar(20) NOT NULL", CanBeNull=false)] public string Nation { get { return this._Nation; } set { if ((this._Nation != value)) { if (this._Nation1.HasLoadedOrAssignedValue) { throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); } this.OnNationChanging(value); this.SendPropertyChanging(); this._Nation = value; this.SendPropertyChanged("Nation"); this.OnNationChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_State", DbType="NVarChar(20)")] public string State { get { return this._State; } set { if ((this._State != value)) { this.OnStateChanging(value); this.SendPropertyChanging(); this._State = value; this.SendPropertyChanged("State"); this.OnStateChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="Nation_Users", Storage="_Nation1", ThisKey="Nation", OtherKey="NationCode", IsForeignKey=true)] public Nation Nation1 { get { return this._Nation1.Entity; } set { Nation previousValue = this._Nation1.Entity; if (((previousValue != value) || (this._Nation1.HasLoadedOrAssignedValue =http://www.mamicode.com/= false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._Nation1.Entity = null; previousValue.Users.Remove(this); } this._Nation1.Entity = value; if ((value != null)) { value.Users.Add(this); this._Nation = value.NationCode; } else { this._Nation = default(string); } this.SendPropertyChanged("Nation1"); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Nation")] public partial class Nation : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private string _NationCode; private string _NationName; private EntitySet<Users> _Users; #region 可扩展性方法定义 partial void onl oaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnNationCodeChanging(string value); partial void OnNationCodeChanged(); partial void OnNationNameChanging(string value); partial void OnNationNameChanged(); #endregion public Nation() { this._Users = new EntitySet<Users>(new Action<Users>(this.attach_Users), new Action<Users>(this.detach_Users)); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NationCode", DbType="NVarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)] public string NationCode { get { return this._NationCode; } set { if ((this._NationCode != value)) { this.OnNationCodeChanging(value); this.SendPropertyChanging(); this._NationCode = value; this.SendPropertyChanged("NationCode"); this.OnNationCodeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NationName", DbType="NVarChar(20) NOT NULL", CanBeNull=false)] public string NationName { get { return this._NationName; } set { if ((this._NationName != value)) { this.OnNationNameChanging(value); this.SendPropertyChanging(); this._NationName = value; this.SendPropertyChanged("NationName"); this.OnNationNameChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="Nation_Users", Storage="_Users", ThisKey="NationCode", OtherKey="Nation")] public EntitySet<Users> Users { get { return this._Users; } set { this._Users.Assign(value); } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private void attach_Users(Users entity) { this.SendPropertyChanging(); entity.Nation1 = this; } private void detach_Users(Users entity) { this.SendPropertyChanging(); entity.Nation1 = null; } } #pragma warning restore 1591
(2)dafault页面布置
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src=http://www.mamicode.com/"js/jquery-1.7.1.min.js"></script> </head> <body> <form id="form1" runat="server"> <table style="width:100%;background-color:blue;text-align:center;"> <thead> <tr style="background-color:aqua"> <td>用户名</td> <td>密码</td> <td>性别</td> <td>昵称</td> <td>生日</td> <td>民族</td> <td>国家</td> </tr> </thead> <tbody id="tb"> <%-- <tr style="background-color:gray"> <td>用户名</td> </tr>--%> </tbody> </table> <input type="button" id="btn1" value=http://www.mamicode.com/"加载" /> </form> </body> </html> <script> $("#btn1").click(function () {//获取全部信息 $.ajax({ url: "ajax/quan.ashx", data: {},//获取全部信息,不需要传值 type: "post", dataType: "json", success: function (aaa) { $("#tb").empty();//加载前线清空内容 for (i in aaa)//aaa为服务处理器quan.ashx所传回来的集合 { var s = ""; s += "<tr style=\"background-color:gray\">"; s += "<td>" + aaa[i].name + "</td>"; s += "<td>" + aaa[i].pwd + "</td>"; s += "<td>" + aaa[i].sex + "</td>"; s += "<td>" + aaa[i].nick + "</td>"; s += "<td>" + aaa[i].bir + "</td>"; s += "<td>" + aaa[i].nation + "</td>"; s += "<td>" + aaa[i].sta + "</td>"; s += "</tr>"; $("#tb").append(s); } }, error: function () { alert("处理器连接失败!"); } }); }); </script>
(3)服务处理器quan.ashx的布置(建立在新建文件夹ajax的里面,与default平级)
<%@ WebHandler Language="C#" Class="quan" %> using System; using System.Web; using System.Linq; using System.Collections.Generic; public class quan : IHttpHandler { //{"name":"","pwd":"","sex":"","nick":"","bir":"","nation":"","sta":""} public void ProcessRequest (HttpContext context) { string n = "["; int count = 0; using (xinxiDataContext cnn = new xinxiDataContext())//拼接含有json的数组:[{"key1":"value1","key2":"value2"},{"key3":"value3"}........{"keyn":"value3"}] { var all = cnn.Users;//等同于 List<ChinaStates> all = cnn.Users.ToList();查询全部信息,返回泛型集合 foreach(Users u in all) { if (count > 0) { n += ","; } n +="{\"name\":\""+u.UserName+"\",\"pwd\":\""+u.Password+"\",\"sex\":\""+u.Sex+"\",\"nick\":\""+u.NickName+"\",\"bir\":\""+u.Birthday+"\",\"nation\":\""+u.Nation+"\",\"sta\":\""+u.State+"\"}"; count++; } } n += "]"; context.Response.Write(n); context.Response.End(); } public bool IsReusable { get { return false; } } }
三、ajax三级联动
(1)建立linq
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.17929 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Linq; using System.Linq.Expressions; using System.Reflection; [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="mydb")] public partial class chinaDataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region 可扩展性方法定义 partial void OnCreated(); partial void InsertChinaStates(ChinaStates instance); partial void UpdateChinaStates(ChinaStates instance); partial void DeleteChinaStates(ChinaStates instance); #endregion public chinaDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString, mappingSource) { OnCreated(); } public chinaDataContext(string connection) : base(connection, mappingSource) { OnCreated(); } public chinaDataContext(System.Data.IDbConnection connection) : base(connection, mappingSource) { OnCreated(); } public chinaDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public chinaDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public System.Data.Linq.Table<ChinaStates> ChinaStates { get { return this.GetTable<ChinaStates>(); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ChinaStates")] public partial class ChinaStates : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private string _AreaCode; private string _AreaName; private string _ParentAreaCode; private bool _Root; private short _Zone; private string _NavigateURL; #region 可扩展性方法定义 partial void onl oaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnAreaCodeChanging(string value); partial void OnAreaCodeChanged(); partial void OnAreaNameChanging(string value); partial void OnAreaNameChanged(); partial void OnParentAreaCodeChanging(string value); partial void OnParentAreaCodeChanged(); partial void OnRootChanging(bool value); partial void OnRootChanged(); partial void OnZoneChanging(short value); partial void OnZoneChanged(); partial void OnNavigateURLChanging(string value); partial void OnNavigateURLChanged(); #endregion public ChinaStates() { OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AreaCode", DbType="VarChar(20) NOT NULL", CanBeNull=false, IsPrimaryKey=true)] public string AreaCode { get { return this._AreaCode; } set { if ((this._AreaCode != value)) { this.OnAreaCodeChanging(value); this.SendPropertyChanging(); this._AreaCode = value; this.SendPropertyChanged("AreaCode"); this.OnAreaCodeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AreaName", DbType="NVarChar(20) NOT NULL", CanBeNull=false)] public string AreaName { get { return this._AreaName; } set { if ((this._AreaName != value)) { this.OnAreaNameChanging(value); this.SendPropertyChanging(); this._AreaName = value; this.SendPropertyChanged("AreaName"); this.OnAreaNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ParentAreaCode", DbType="VarChar(20) NOT NULL", CanBeNull=false)] public string ParentAreaCode { get { return this._ParentAreaCode; } set { if ((this._ParentAreaCode != value)) { this.OnParentAreaCodeChanging(value); this.SendPropertyChanging(); this._ParentAreaCode = value; this.SendPropertyChanged("ParentAreaCode"); this.OnParentAreaCodeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Root", DbType="Bit NOT NULL")] public bool Root { get { return this._Root; } set { if ((this._Root != value)) { this.OnRootChanging(value); this.SendPropertyChanging(); this._Root = value; this.SendPropertyChanged("Root"); this.OnRootChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Zone", DbType="SmallInt NOT NULL")] public short Zone { get { return this._Zone; } set { if ((this._Zone != value)) { this.OnZoneChanging(value); this.SendPropertyChanging(); this._Zone = value; this.SendPropertyChanged("Zone"); this.OnZoneChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NavigateURL", DbType="VarChar(100)")] public string NavigateURL { get { return this._NavigateURL; } set { if ((this._NavigateURL != value)) { this.OnNavigateURLChanging(value); this.SendPropertyChanging(); this._NavigateURL = value; this.SendPropertyChanged("NavigateURL"); this.OnNavigateURLChanged(); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } #pragma warning restore 1591
(2)web窗体页面布置
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src=http://www.mamicode.com/"js/jquery-1.7.1.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="sheng_dd" runat="server"></asp:DropDownList> <asp:DropDownList ID="shi_dd" runat="server"></asp:DropDownList> <asp:DropDownList ID="qu_dd" runat="server"></asp:DropDownList> </div> </form> </body> </html> <script> bind($("#sheng_dd"),"0001","1"); function bind(drop,pcode,aa) { $.ajax({ url: "ajax/China.ashx", data: { "pcode": pcode }, type: "post", dataType: "json", success: function (aaa) {//aaa为数据处理完毕返回来的数组 if (aa == "1") {//如果aa=1,给省加载。 drop.empty(); for (i in aaa) { var a = "<option value=http://www.mamicode.com/"" + aaa[i].code + "\">" + aaa[i].name + "</option>";//DropDownList在页面编译成select,所以用<option value="">text</option> drop.append(a);//循环往DropDownList增加数据 } bind($("#shi_dd"), $("#sheng_dd").val(), "2"); bind($("#qu_dd"), $("#shi_dd").val(), "3"); } if (aa == "2")//如果aa=2,给市加载。 { drop.empty(); for (i in aaa) { var a = "<option value=http://www.mamicode.com/"" + aaa[i].code + "\">" + aaa[i].name + "</option>";//DropDownList在页面编译成select,所以用<option value="">text</option> drop.append(a);//循环往DropDownList增加数据 } bind($("#qu_dd"), $("#shi_dd").val(), "3"); } if (aa == "3")//如果aa=3,给区加载。 { drop.empty(); for (i in aaa) { var a = "<option value=http://www.mamicode.com/"" + aaa[i].code + "\">" + aaa[i].name + "</option>";//DropDownList在页面编译成select,所以用<option value="">text</option> drop.append(a);//循环往DropDownList增加数据 } } }, error: function () { alert("服务器连接失败"); }//error });//ajax };//bind() $("#sheng_dd").change(function () {//sheng_dd所选变化事件 bind($("#shi_dd"), $("#sheng_dd").val(), "2");//市根据省变化 }); $("#shi_dd").change(function () {//shi_dd所选变化事件 bind($("#qu_dd"), $("#shi_dd").val(), "3");//区根据市变化 }); </script>
(3)服务处理器China.ashx页面,(建立在新建文件夹ajax的里面,与default平级)
<%@ WebHandler Language="C#" Class="China" %> using System; using System.Web; using System.Collections.Generic; using System.Linq; using System.Text; public class China : IHttpHandler { public void ProcessRequest (HttpContext context) {//此处的作用就是拼接含有json的数组,格式[{"key1";:"value1","key2":"value2"}.....{"keyn":"valuen"}] string pcode=context.Request["pcode"];//接收传过来的数据 StringBuilder s = new StringBuilder(); int count = 0; s.Append("["); using (chinaDataContext con = new chinaDataContext()) { List<ChinaStates> list = con.ChinaStates.Where(r => r.ParentAreaCode == pcode).ToList();//根据ParentAreaCode查询符合条件的地区 foreach (ChinaStates c in list) { if (count > 0) { s.Append(","); } s.Append("{\"code\":\""+c.AreaCode+"\",\"name\":\""+c.AreaName+"\"}"); count++; } } s.Append("]"); context.Response.Write(s); context.Response.End(); } public bool IsReusable { get { return false; } } }
完!!
ajax验证表单元素规范正确与否 ajax展示加载数据库数据 ajax三级联动