ASP.NET MVC + Jquery 实现Ajax下拉框数据三级联动

这是第一使用Jquery实现城市三级数据联动的实例!之前本人没有使用过Jquery,在WebForm的开发过程中,很多时候用的是ASP.NET Ajax,ajaxPro +JavaScript,从未使用过JS框架,最近在学习ASP.NET MVC,在最新的发布版本中,已经集成了Jquery 1.3.1,自然,也要学一学!发现使用Jquery代码果然写得比原始JS优雅!只是语法和方法太多,现在还没弄熟,还需要时间来学习.....这次是第一次使用Jquery写客户端脚本,如果大家发现更好的实现方法,请给我留言!谢谢!

注明:ASP.NET MVC 1.0 ,作者:0x001;

View:

<script type="text/javascript">
    $(document).ready(function() {
        GetByJquery();
        $("#ddlProvince").change(function() { GetCity() });
        $("#ddlCity").change(function() { GetDistrict() });
    });
    
    function GetByJquery() {

        $("#ddlProvince").empty(); //清空省份SELECT控件

        $.getJSON("/ajax/GetProvinceList", function(data) {
            $.each(data, function(i, item) {
                $("<option></option>")
                    .val(item["ProvinceID"])
                    .text(item["ProvinceName"])
                    .appendTo($("#ddlProvince"));
            });
            GetCity();
        });     

    }

    function GetCity() {

        $("#ddlCity").empty(); //清空城市SELECT控件
        var url ="/ajax/GetCityList/" + $("#ddlProvince").val();
        $.getJSON(url, function(data) {
            $.each(data, function(i, item) {
                $("<option></option>")
                    .val(item["CityID"])
                    .text(item["CityName"])
                    .appendTo($("#ddlCity"));
            });
            GetDistrict();
        });
    }

    function GetDistrict() {
        $("#ddlDistrict").empty(); //清空市区SELECT控件
        var url = "/ajax/GetDistrictList/" + $("#ddlCity").val();
        
        $.getJSON(url, function(data) {
            $.each(data, function(i, item) {
                $("<option></option>")
                    .val(item["DistrictID"])
                    .text(item["DistrictName"])
                    .appendTo($("#ddlDistrict"));
            });
        });
    }

</script>
<table><tr><td><select id="ddlProvince"/></td><td><select id="ddlCity"/></td><td><select id="ddlDistrict" /></td></tr></table>

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcBBS.Controllers
{
    public class AjaxController : Controller
    {
        //
        // GET: /Ajax/

        /// <summary>
        /// 获取所有[省份]数据
        /// </summary>
        public ActionResult GetProvinceList()
        {
            if (!Request.IsAjaxRequest())
            {
                return Content("请不要非法方法,这是不道德的行为!");
            }

            BLL.Province bll = new MvcBBS.BLL.Province();
            List<MvcBBS.Model.S_Province> modellist = bll.GetProvinceList();

            return Json(modellist);
        }

        /// <summary>
        /// 获取某[省份]的所有[城市]数据
        /// </summary>
        public ActionResult GetCityList(int id)
        {
            if (!Request.IsAjaxRequest())
            {
                return Content("请不要非法方法,这是不道德的行为!");
            }
            BLL.Province bll = new MvcBBS.BLL.Province();
            List<MvcBBS.Model.S_City> modellist = bll.GetCityList(id);
            return Json(modellist);
        }

        /// <summary>
        /// 获取某[城市]的所有[市区]数据
        /// </summary>
        public ActionResult GetDistrictList(int id)
        {
            if (!Request.IsAjaxRequest())
            {
                return Content("请不要非法方法,这是不道德的行为!");
            }

            BLL.Province bll = new MvcBBS.BLL.Province();
            List<MvcBBS.Model.S_District> modellist = bll.GetDistrict(id);

            return Json(modellist);
        }

    }
}

我比较喜欢使用三层+工厂模式来读写数据,O/R Mapping不太适合我的要求!我们写的项目经常不是为了方便移植,而是选择明确的数据库,需要更高的性能,更强的业务逻辑!大家看到上面的代码,应该很熟悉,从数据库读数据到List<>中返回,并使有ASP.NET MVC内置的Json方法转换数据并Response.

DAL:    

// BLL,Model就不贴出来了!

using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;
using DBUtility;//请先添加引用

namespace MvcBBS.DAL
{
    public class Province
    {
        public Province()
        {}

        /// <summary>
        /// 获取所有省份数据
        /// </summary>
        /// <returns></returns>
        public List<Model.S_Province> GetProvinceList()
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT ProvinceID,ProvinceName ");
            strSql.Append(" FROM S_Province ");
            List<Model.S_Province> modelList = new List<MvcBBS.Model.S_Province>();
            SqlDataReader dr = DbHelperSQL.ExecuteReader(strSql.ToString());            
            while (dr.Read())
            {
                 Model.S_Province _model = new MvcBBS.Model.S_Province();
                 _model.ProvinceID = int.Parse(dr["ProvinceID"].ToString());
                 _model.ProvinceName = dr.GetString(1);
                modelList.Add(_model);
            }
            dr.Close();
            return modelList;
        }

        /// <summary>
        /// 获取某省份的所有城市数据
        /// </summary>
        /// <param name="ProvinceID"></param>
        /// <returns></returns>
        public List<Model.S_City> GetCityList(int ProvinceID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT CityID,CityName,ZipCode");
            strSql.Append(" FROM S_City ");
            strSql.Append(" WHERE ProvinceID=");
            strSql.Append(ProvinceID.ToString());

            List<Model.S_City> modelList = new List<MvcBBS.Model.S_City>();
            SqlDataReader dr = DbHelperSQL.ExecuteReader(strSql.ToString());
            while (dr.Read())
            {
                Model.S_City _model = new MvcBBS.Model.S_City();
                _model.CityID = int.Parse(dr["CityID"].ToString());
                _model.CityName = dr.GetString(1);
                _model.ZipCode = dr.GetString(2);
                _model.ProvinceID = ProvinceID;
                modelList.Add(_model);
            }
            dr.Close();
            return modelList;
        }

        /// <summary>
        /// 获取某城市的所有市区
        /// </summary>
        /// <param name="CityID"></param>
        /// <returns></returns>
        public List<Model.S_District> GetDistrict(int CityID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT DistrictID,DistrictName");
            strSql.Append(" FROM S_District ");
            strSql.Append(" WHERE CityID=");
            strSql.Append(CityID.ToString());

            List<Model.S_District> modelList = new List<MvcBBS.Model.S_District>();
            SqlDataReader dr = DbHelperSQL.ExecuteReader(strSql.ToString());
            while (dr.Read())
            {
                Model.S_District _model = new MvcBBS.Model.S_District();
                _model.DistrictID = int.Parse(dr["DistrictID"].ToString());
                _model.DistrictName = dr.GetString(1);
                _model.CityID = CityID;
                modelList.Add(_model);
            }
            dr.Close();
            return modelList;
        }
    }
}

转载请注明: 0x001.com ,谢谢!大家多多提点建议!本人需要学习和改进的动力! 

你可能感兴趣的:(asp.net)