基于jQuery+ashx+.net实现三级栏目联动操作

父级ID可以为空以两个编号为一级 可以添加到第四级

table 字段有ID、 name 、parentNode、 childNode等基本属性  selecet  parentNode  ,len(childNode)/2 as level,...... from table

<table id="tableList">  </table> id列表显示属性HTML省略

html:

<div id="dialog-form" title="新增|修改" style="display: none;">

        <p class="validateTips">

        </p>

        <label for="parentNode" style="float: left">

            父级栏目:</label>

        <select id="SelectNode" style="height: 22px">

            <option value="-1">请选择</option>

        </select>

        <select id="SelectNode2" style="height: 22px">

            <option value="-1">请选择</option>

        </select>

        <select id="SelectNode3" style="height: 22px">

            <option value="-1">请选择</option>

        </select><p>

        </p>

        <p>

        </p>

        

        <label for="nodecode" style="float: left">

            栏目编号:</label>

        <input type="text" name="nodecode1" id="nodecode1" style="width: 72px; background-color: #cacaca;"

            maxlength="2" readonly="readonly" />

        <%--一级栏目编号--%>

        <input type="text"   name="nodecode2" id="nodecode2" style="width: 72px;" maxlength="2"

            onkeyup="lengthLimit(this)"    />

        <%--二级栏目编号--%>

        <p>

        </p>

        <label for="menuName" style="float: left">

            栏目名称:</label>

        <input type="text" name="menuName" id="menuName"   maxlength="20" onkeyup="checkNull(this)" style="width: 



200px" /><p>

        </p>   

       <label for="icoUrl" style="float: left">

            栏目图标:</label>

        <div>

            <div id="J_imageView" style="margin-left: 50px">

                <img alt="" id="img_rs_stu" style="width: 32px; height: 32px" src="" />

            </div>

            <div style="margin-left: 70px; margin-top: 5px; border-bottom: 5px">

                <input type="button" id="uploadButton" value="上传" style="height: 50px; width: 110px;

                    float: left;" />

            </div>

        </div>

        <p>

        </p>

    </div>



<div class="ctent">

            <input type="button" id="create-menu" value="新增栏目" />

        </div>
View Code

js:

js

<script type="text/javascript">

        

           var iType = 0;



             //新增栏目操作

            $("#create-menu").button().click(function () {

                BindChange();

                IniteDropDown([]);

                tag = "add";

                $("#dialog-form").dialog("open");

                $.post("/ashx/menusHandler.ashx", { fun: 'getMaxNum', type: iType }, function (data, status) {

                    $('#num').attr("disabled", "disabled")

                    $("#num").val(data);

                });

            });

        });

        //初始化下拉框

        function IniteDropDown(c) {

            //清除

            $("#SelectNode > option[value!='-1']").remove();

            $("#SelectNode2 > option[value!='-1']").remove();

            $("#SelectNode3 > option[value!='-1']").remove();

            //加载下拉框数据 一级二级三级栏目联动

            IniteSelect({

                ids: ['SelectNode', 'SelectNode2', 'SelectNode3'],

                swType: ['GetCloumn', 'GetCloumn', 'GetCloumn'], BaseUrl: '/ashx/DropDownControl.ashx?aktype=' + 



iType,

                callBack: c

            });

        }

  //栏目下拉选择节点名称值赋给文本框 获取 父节点的栏目名称编号

        //change 选项注册事件 根据下拉后赋值给控件

        function BindChange() {

            $("#SelectNode").change(function () { //当第一个下拉列表变动内容时第二个下拉列表将会显示

                var temp = $(this).val();

                if (temp == '-1') temp = ''; //选项为-1时 文本值为空

                $("#nodecode1").val(temp)//当第一个下拉列表变动内容时栏目编号显示父级编号

            }

            );

            //二级下拉框事件

            $("#SelectNode2").change(function () {

                var temp = $(this).val();

                if (temp == '-1') temp = $('#SelectNode').val();//显示父节点编号

                if (temp == '-1') temp = ''; //文本值编号为空

                $("#nodecode1").val(temp)



            }

          );

            //三级下拉框事件

            $("#SelectNode3").change(function () {

                var temp = $(this).val();

                if (temp == '-1') temp = $('#SelectNode2').val();

                if (temp == '-1') temp = $('#SelectNode').val();

                if (temp == '-1') temp = '';

                $("#nodecode1").val(temp)

            }

          );

        }

   

         //初始化加载数据获取列表信息

        function GetData() {

            InitPager({

                PageId: "#paging",

                Url: "/ashx/menusHandler.ashx",

                Options: { fun: "list", type: iType }, 

                CallBack: function (result) {

                    $('#tbody').html('');

                    $("#menuDemo").tmpl(result.Rows).appendTo("#tbody");

                    return result.Total;

                }

            });

        }



        var tag, strGuid;

        var aaa = false;

        var imgurl = "";



     $(function () {



            GetData();



            $("#dialog-form").dialog({

                autoOpen: false,

                bgiframe: true,

                height: 400,

                width: 400,

                modal: true,

                buttons: {

                    "保 存": function () {

                        var bValid = true;



                        var nodecode1 = $("#nodecode1").val(); //栏目一级编号

                        var nodecode2 = $("#nodecode2").val(); //栏目二级编号

                        var childnode = nodecode1 + nodecode2;  //子节点

                        

                        var menuname = $("#menuName").val();

                        var icoUrl = imgurl;

                        if (nodecode2=='' || nodecode2.length < 2) {

                            bValid = false;

                            updateTips("编号不能为空且长度不能小于两位!");

                            

                        }

                        if (menuname =='') {

                            bValid = false;

                            updateTips("栏目名称必填!");

                        }

                        

                        if (bValid) {

                            $.post('/ashx/menusHandler.ashx', { fun: 'save', nodecode1: nodecode1, menuname: 



menuname, icoUrl: imgurl, type: iType, tag: tag, guid: strGuid, childnode: childnode }, function (status) {

                                if (status == "OK") {

                                    ReflashPager();

                                    alertmessage("操作提示", "信息保存成功!", null);

                                }

                                else {

                                    alertmessage("保存失败!编号不能与已存在编号相同!");

                                }

                            });

                            $(this).dialog("close");

                        }

                    },

                    "取 消": function () {

                        $(this).dialog("close");

                    }

                },

                open: function (event, ui) {

                    //文件上传

                    if (!aaa) {

                        var K = KindEditor;

                        var uploadbutton = K.uploadbutton({

                            button: K('#uploadButton')[0],

                            fieldName: 'imgFile',

                            url: '/ashx/FileUploadHandler.ashx?filetype=logo',

                            afterUpload: function (data) {

                                if (data.error === 0) {

                                    var url = K.formatUrl(data.url, 'absolute');

                                    var div = K('#J_imageView');

                                    div.html('');

                                    div.append('<img src="' + url + '" style="width: 32px; height: 32px;"/>');

                                    K('#url1').val(url);

                                    imgurl = url;

                                } else {

                                    alert(data.message);

                                }

                            },

                            afterError: function (str) {

                                alert('自定义错误信息: ' + str);

                            }

                        });

                        uploadbutton.fileBox.change(function (e) {

                            uploadbutton.submit();

                        });

                        aaa = true;

                    }

                },

                close: function () {

                    $("#nodecode1").val('');

                    $("#nodecode2").val('');

                    $("#menuName").val('');

                    

                    $("#img_rs_stu").attr('src', '');

                    $("#nodecode").removeAttr("disabled").css('background', '');

                    RemoveChange();

                }

            });



</script>
View Code

DropDownControl.ashx 代码:

 /// <summary>

        /// 获取栏目下拉   

        /// </summary>

        /// <param name="form"></param>

        public void GetCloumn(NameValueCollection form)

        { 

            //此处查询节点

            var pcode = form["guid"];



            var aktype = HttpContext.Current.Request.QueryString["aktype"];

            ak_menus bll = new ak_menus();

            var tb = bll.GetMenus(pcode, aktype); //根据传递参数 获取数据信息操作了



            SerializeResponse(tb,"name");

        }



    }



     public static void SerializeResponse(DataTable tb, string name)

        {

            List<DropDown> list = new List<DropDown>();

            

            foreach (DataRow row in tb.Rows)

            {

                DropDown at = new DropDown();

                at.Value = row["guid"].ToString();

                if (string.IsNullOrEmpty(name))

                {

                    at.Text = row[name].ToString();

                }

                else

                {

                   

                }

                list.Add(at);

            }

            AshxHelper.Write(list);

        }
View Code

FileUploadHandler.ashx 代码:

public override void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";

            if (ValidateUser())

            {   

                try

                {

                    //文件所在文件夹路径:每次相关的文章或者广告名,附加路径

                    var filedir = context.Request.QueryString["filedir"];



                    //上传类别,根据类别获取配置文件

                    var filetype = context.Request.QueryString["filetype"];



                    string configUrl = XiuxiuUploadHelper.GetConfigURl(filetype);

                    if (context.Request.Files.Count > 0)

                    {

                        HttpPostedFile UploadFile = context.Request.Files["imgFile"];

                        UploadFile = (UploadFile == null) ? context.Request.Files["mediaFile"] : UploadFile;



                        if (UploadFile != null)

                        {

                            //定义允许上传的文件扩展名

                            ArrayList exts = new ArrayList() { "image", "flash", "media", "file" };



                            //上传图片:上传文件后返回上传结果

                            string dirName = context.Request.QueryString["dir"];

                            if (string.IsNullOrEmpty(dirName))

                            {

                                dirName = "image";

                            }



                            if (!exts.Contains(dirName))

                            {

                                //不允许的上传类型

                                showError(context, "不允许的上传的文件类型.");

                            }



                            //执行文件上传构造函数

                            Ak_UploadHelper FupdHelper = new Ak_UploadHelper(context.Request.Files[0], configUrl, filedir);



                            //执行文件上传

                            string FileURLOfServer = FupdHelper.UploadFileFromHtpostfile();

                            if (!string.IsNullOrEmpty(FileURLOfServer) && FileURLOfServer.Equals(Ak_UploadHelper.UpLoadResult.SUCCESS.ToString()))

                            {

                                Hashtable hash = new Hashtable();

                                hash["error"] = 0;

                                hash["url"] = FupdHelper.CustomUploadPath;

                                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");

                                AshxHelper.Write(hash);

                            }

                            else

                            {

                                showError(context, FileURLOfServer);

                            }

                        }

                    }

                    else

                    {



                        //保存秀秀上传图片 主要是头像

                        var result = XiuxiuUploadHelper.SaveXiuxiuPhoto(context, configUrl, filedir);

                        AshxHelper.Write(result);

                    }



                }

                catch (Exception e)

                {

                    throw new Exception("上传文件失败!" + e);

                }



            }

            else

            {

                throw new Exception("当前用户无操作权限!");

            }



        }



     private void showError(HttpContext context, string message)

        {

            Hashtable hash = new Hashtable();

            hash["error"] = 1;

            string UploadRsZh_CN = Ak_UploadHelper.GetUploadRsOfZh_CN(message);

            hash["message"] = UploadRsZh_CN;

            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");

            AshxHelper.Write(hash);

        }

     }
View Code

menusHandler.ashx 代码:

public override void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";



            if (ValidateUser())

            {

                StringBuilder strBuilder = new System.Text.StringBuilder();

                string strFun = context.Request.Form["fun"];

                switch (strFun)

                {

                    

                    case "save":

                        string strNodeCode = context.Request.Form["nodecode1"];

                        string strMenuName = context.Request.Form["menuname"];

                        string strUrl = context.Request.Form["menuurl"];

                        string strType = context.Request.Form["type"];

                        string strIco = context.Request.Form["icoUrl"];

                        string tag = context.Request.Form["tag"];

                        

                        string strChildNode = context.Request.Form["childnode"];//子节点

                        

                        if (string.IsNullOrWhiteSpace(strMenuName) && strChildNode == null || strChildNode.Length < 2)

                        {

                            AshxHelper.Write(false);

                            break;

                        }

                        var result = false;

                        if (tag == "add") //添加

                        {   //判断名称是否为空



                            result = addMenu(strNodeCode, strMenuName, strUrl, strType, strIco, num, strChildNode, ispopular);



                        }

                        else

                        {     //修改

                            string strguid = context.Request.Form["guid"];

                            result = editMenu(strNodeCode, strMenuName, strUrl, strType, strIco, num, ispopular, strguid, strChildNode);



                        }

                        AshxHelper.Write(result);

                        break;

                    case "set":  //列表框信息设置

                        string strGuid = context.Request.Form["guid"];

                        string strState = context.Request.Form["akState"];

                        if (setState(strGuid, strState))

                            strBuilder.Append("success");

                        else

                            strBuilder.Append("error");

                        context.Response.Write(strBuilder);

                        break;

                    case "model"://编辑修改操作获取信息

                        string guid = context.Request.Form["guid"];

                        context.Response.Write(getModel(guid));

                        break;

                    case "list"://获取列表信息初始加载数据

                        GetList(context.Request.Form);

                        break;

                    case "getMaxNum":// 根据类型获取最大序列号值

                        getMaxNum(context.Request.Form);

                        break;

                }

            }

            else

            {

                throw new Exception("当前用户无操作权限!");

            }

        }

              

        /// <summary>

        /// 根据类型获取最大序列号值

        /// </summary>

        /// <param name="form"></param>

        void getMaxNum(NameValueCollection form)

        {

            int type = Convert.ToInt32(form["type"].ToString());

            int num = bll.getMaxNum(type);  //数据操作查询方法



            AshxHelper.Write(num);

            

        }



       /// <summary>

        /// 获取数据列表信息

        /// </summary>

        /// <param name="form"></param>

        void GetList(NameValueCollection form)

        {

            var type = form["type"];

            var pageIndex = form["pageIndex"];

            var pageSize = form["pageSize"];



            var table = base.GetPagination("guid,lcon,name,url,akState,num,Lev",

                "v_menus", "nodecode", out DoCount, string.Format("AND aktype = '{0}' ", AnkeEdu.Tools.SqlEncodeHelper.EncodeSqlParam(type)));



            AshxHelper.Write(new { Total = DoCount, Rows = table });

            

        }



       /// <summary>

        /// 添加栏目

        /// </summary>

        /// <param name="strNode"></param>

        /// <param name="strName"></param>

        /// <param name="strUrl"></param>

        /// <returns></returns>

        private bool addMenu(string strNode, string strName, string strType, string strIco,  string strChildNode)//添加子节点strChildNode

        {

            //检测是否重复

            if (!bll.IsRepeat(new Guid(), strChildNode))

            {

                AnkeEdu.Model.ak_menus model = new AnkeEdu.Model.ak_menus();

                model.guid = AnkeEdu.Tools.NewId.NewUpGuid();

                model.akState = 1;

                model.aktype = Convert.ToInt32(strType);

                model.name = strName;

 

                model.lcon = strIco;

                model.addTime = DateTime.Now;

                model.NodeCode = strChildNode;//赋值子节点

                model.ParentNode = strNode;

                return bll.Add(model); //添加操作数据信息

            }

            return false;

        }



        /// <summary>

        /// 编辑修改

        /// </summary>

        /// <param name="strNode"></param>

        /// <param name="strName"></param>

        /// <param name="strIco"></param>

        

        /// <param name="guid"></param>

        /// <returns></returns>

        private bool editMenu(string strNode, string strName,  string strType, string strIco,  string guid,string strChildNode)

        {

            

            var g = new Guid(guid);

            if (!bll.IsRepeat(g, strChildNode)) //检测是否重复

            {

                Model.ak_menus model = new Model.ak_menus();

                model = bll.GetModel(g);//根据ID获得实体信息

                model.aktype = Convert.ToInt32(strType);

                model.name = strName;

                model.lcon = strIco;

                model.ParentNode = strNode;

               

                model.NodeCode = strChildNode;



                return bll.Update(model); //数据更新操作

            }

            return false;

        }

       /// <summary>

        /// 根据ID获取信息

        /// </summary>

        /// <param name="guid"></param>

        /// <returns></returns>

        private string getModel(string guid)

        {

            return JsonConvert.SerializeObject(bll.GetModel(new Guid(guid))); //数据操作构造函数

        }
View Code

效果图:

基于jQuery+ashx+.net实现三级栏目联动操作

列表信息显示效果图

基于jQuery+ashx+.net实现三级栏目联动操作

你可能感兴趣的:(jquery)