C#.MVC+JQuery1.9自定义下拉框控件

Controllers:

Controllers:
namespace MvcJSCommon.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public static class HtmlExtensions 
    {
        /// <summary>
        /// 自定义下拉框控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="name">控件名</param>
        /// <param name="source">列表源</param>
        /// <param name="exprValue">绑定值字段</param>
        /// <param name="exprText">绑定文本字段</param>
        /// <param name="defaultVal">默认值,可为null</param>
        /// <param name="htmlAttributes">html属性,可为null</param>
        /// <param name="edit">是否可编辑</param>
        /// <returns></returns>
        public static MvcHtmlString DropDownListCustom<T>
  (this HtmlHelper htmlHelper, string name, IEnumerable<T> source, Expression<Func<T, object>> exprValue
            , Expression<Func<T, object>> exprText, object defaultVal = null, object htmlAttributes = null, bool edit = false)
        {

            return MvcHtmlString.Create(DropDownListCustomHtml(name, source, exprValue, exprText, defaultVal, htmlAttributes, edit));
        }
        /// <summary>
        /// 生成下拉html代码重载
        /// </summary>
        /// <typeparam name="T">绑定实体类型</typeparam>
        /// <param name="name">Comobx的ID</param>
        /// <param name="source"></param>
        /// <param name="exprValue"></param>
        /// <param name="exprText"></param>
        /// <param name="defaultVal"></param>
        /// <param name="htmlAttributes"></param>
        /// <param name="edit"></param>
        /// <returns></returns>
        public static string DropDownListCustomHtml<T>(string name, IEnumerable<T> source, Expression<Func<T, object>> exprValue, Expression<Func<T, object>> exprText, object defaultVal = null, object htmlAttributes = null, bool edit = false)
        {
            List<SelectListItem> selectList = new List<SelectListItem>();

            if (exprValue != null && exprText != null)
            {
                var handlerValue = exprValue.Compile();
                var handlerText = exprText.Compile();
                if (source == null)
                {
                    source = new List<T>();
                }
                foreach (var i in source)
                {
                    var value = (handlerValue.Invoke(i) ?? new object()).ToString();
                    var text = (handlerText.Invoke(i) ?? new object()).ToString();
                    var selected = (defaultVal != null && defaultVal.ToString().Equals(value, StringComparison.OrdinalIgnoreCase));
                    selectList.Add(new SelectListItem()
                    {
                        Value = value,
                        Text = text,
                        Selected = selected
                    });
                }
            }

            return DropDownListCustomHtml(name, selectList, htmlAttributes, edit);
        }
        /// <summary>
        /// 生成下拉html代码
        /// </summary>
        /// <param name="name"></param>
        /// <param name="selectList"></param>
        /// <param name="htmlAttributes">样式处理只能以下几个new {@classinput="xxx",@inputwidth="110",@classdropdiv="drop",@dropdivwidth="20",@classselectdiv="selectDiv",@selectdivheight="100"}</param>
        /// <returns></returns>
        private static string DropDownListCustomHtml(string name, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool edit = false)
        {

            StringBuilder attrs = new StringBuilder();
            #region 样式处理
            string classTop = "select";
            string width = "", height = "";

            if (htmlAttributes != null)
            {
                var t = htmlAttributes.GetType();
                foreach (var property in t.GetProperties())
                {
                    switch (property.Name.ToLower())
                    {
                        case "class"://总的样式
                            classTop = property.GetValue(htmlAttributes, null).ToString();
                            break;
                        case "width":       //宽
                            width = property.GetValue(htmlAttributes, null).ToString();
                            break;
                        case "height":      //高
                            height = property.GetValue(htmlAttributes, null).ToString();
                            break;
                         default:
                            break;
                    }


                }
            }
            #endregion

            StringBuilder sb = new StringBuilder();
            string defaultText = string.Empty;
            string defaultValue = string.Empty;

            StringBuilder sbText = new StringBuilder();

            if (!selectList.IsNullOrEmpty())
            {
                defaultText = selectList.ElementAt(0).Text;
                defaultValue = selectList.ElementAt(0).Value;
                //是否有默认值
                var model = from c in selectList
                            where c.Selected == true
                            select c;
                if (!model.IsNullOrEmpty())
                {
                    defaultText = model.ElementAt(0).Text;
                    defaultValue = model.ElementAt(0).Value;
                }
                foreach (var item in selectList)
                {
                    sbText.AppendFormat("<li itemvalue=\"{0}\">{1}</li>", item.Value, item.Text);
                }
            }

            if (!string.IsNullOrEmpty(width))
            {
                width = string.Format("width:{0}px;", width);
            }
            if (!string.IsNullOrEmpty(height))
            {
                height = string.Format("height:{0}px;", height);
            }

            sb.AppendFormat("<div id=\"divComBox_{0}\" class=\"{1}\" tabindex=\"0\"  style=\"{2}{3}\">", name, classTop, width, height);
            sb.AppendFormat("<input type=\"text\" id=\"divComBox_Text_{0}\" value=\"{1}\" {2} />",name,defaultText,edit?"":"readonly=\"readonly\"");
            sb.AppendFormat("<input type=\"hidden\" id=\"divComBox_Value_{0}\" value=\"{1}\" />",name,defaultValue);
            sb.AppendFormat("<ul>{0}</ul>",sbText);
            sb.Append("</div>");

            return sb.ToString(); 
        }
    }
}
namespace System
{
    public static class SystemEx
    {
        /// <summary>
        /// 判断一个List是否为空或者Count=0
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="list">列表</param>
        /// <returns>是否为空</returns>
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> list)
        {
            if (list == null)
                return true;

            if (list.Count() == 0)
                return true;

            return false;
        }
    }
}
View Code
Controllers:
public ActionResult DDlTest()  
{  
    ViewBag.Message = "下拉框控件-黑色样式";  
    List<TestInfo> list = new List<TestInfo>();  
    for (int i = 0; i < 50; i++)  
    {  
        list.Add(new TestInfo  
        {  
            UserName = "UserName" + i.ToString(),  
            UserID = "UserID" + i.ToString(),  
            UserSEX = "UserSEX" + i.ToString(),  
            UserAddress = "UserAddress" + i.ToString()  
        });  
    }  
    ViewData["DDLList"] = list;  
    return View();  
}  
View Code
public class TestInfo  
{  
    public string UserName { get; set; }  
    public string UserID { get; set; }  
    public string UserSEX { get; set; }  
    public string UserAddress { get; set; }  
} 
View Code
DDLTest.aspx:
<script type="text/javascript">  
    $(document).ready(function () {  
       CustomComBox.Bind('TestDDL');  //初始化控件,不然用不了  
    });  
</script>  
View Code
<div style="background: #222;padding:5px 5px 5px 5px;margin: 3px; text-align: right;" >  
            <%=Html.DropDownListCustom("TestDDL", ViewData["DDLList"] as List<TestInfo>, c => c.UserID, c => c.UserName, null, new { @class = "SelectDDL" }, true)%>  
            </div>
View Code
comboBox.js
   //主控件点击事件  
        var funcOnClickComBox = function (objID) {  
            var divComboBox = $(this);  
            var txtComboBox = divComboBox.find(":text");  
            divComboBox.children("ul").toggle(0, function () {  
                if ($(this).is(":visible")) {   
                    txtComboBox.focus();   
                } else {  
                }  
            });  
        }  
 //初始化  
        var funcComBoxEventBind = function (objID) {  
            //debugger  
            var divComboBox = $("#divComBox_" + objID)  
            var ulComboBox = divComboBox.find("ul");  
            var txtComboBox = divComboBox.find(":text");  
            var valueComboBox = divComboBox.find(":input[type='hidden']");  
            var liList = divComboBox.find("li");  
            var mouseInDiv = false;  
            //主控件点击事件:显示下拉列表  
            divComboBox.bind("click", funcOnClickComBox);  
            //设置内文本框宽度  
            txtComboBox.width(divComboBox.innerWidth() - 30 - 5);  
            //设置下拉列表弹出的位置   
            ulComboBox.css("left", txtComboBox.position().left);  
            ulComboBox.css("top", txtComboBox.position().top + txtComboBox.outerHeight());  
            ulComboBox.width(txtComboBox.outerWidth() - 2);  
            //列表项点击事件  
            liList.each(function (i, n) {  
                $(this).bind('click', function () {  
                    //清除所有选中  
                    liList.attr({ "selected": false });  
                    liList.removeClass("selected");  
                    //设置点击项为当前选中项  
                    $(this).attr({ "selected": true });  
                    $(this).addClass("selected");  
                    //取值赋值  
                    txtComboBox.val($(this).text());  
                    var oldValue = valueComboBox.val();  
                    valueComboBox.val($(this).attr("itemValue"));  
                    if (oldValue != valueComboBox.val()) {  
                        txtComboBox.trigger('change');  
                    }  
                    txtComboBox.focus();  
                });  
            });  
            var mouseinout = $("#mouseinout");  
            divComboBox.hover(function () {  
                mouseInDiv = true;  
                mouseinout.html("mouse In");  
            }, function () {  
                mouseInDiv = false;  
                mouseinout.html("mouse Out");  
            });  
            //控件失去焦点事件:隐藏下拉列表  
            txtComboBox.blur(function () {  
                if (!mouseInDiv && ulComboBox.css("display") == "block") {  
                    ulComboBox.css("display", "none");  
                }  
            });  
            divComboBox.blur(function () {  
                if (!mouseInDiv && ulComboBox.css("display") == "block") {  
                    ulComboBox.css("display", "none");  
                }  
            });  
            //            //鼠标离开事件    若想要此功能则去掉注即可  
            //            ulComboBox.mouseleave(function () {  
            //                if ($(this).css("display") == "block") {  
            //                    $(this).css("display", "none");  
            //                }  
            //            });  
            //回车事件  
            txtComboBox.bind('keydown', function () {  
                //回车  
                if (event.keyCode == 13) {  
                    var queryselect = false;  
                    for (var i = 0; i < liList.length; i++) {  
                        if ($(liList[i]).attr("selected")) {  
                            //附值Text  
                            txtComboBox.val($(liList[i]).text());  
                            //附值Value  
                            valueComboBox.val($(liList[i]).attr("itemvalue"));  
                            queryselect = true;  
                            break;  
                        }  
                    }  
                    if (queryselect == false) {  
                        if (ulComboBox.css("display") == "none") {  
                            ulComboBox.css("display", "block");  
                        }  
                    }  
                    else {  
                        if (ulComboBox.css("display") == "block") {  
                            ulComboBox.css("display", "none");  
                        }  
                    }  
                }  
            });  
            //按键输入事件  
            txtComboBox.bind('keyup', function () {  
                //不处理回车事件  
                if (event.keyCode == 13) {  
                    return;  
                }  
                if (ulComboBox.css("display") == "none") {  
                    ulComboBox.css("display", "block");  
                }  
                valueComboBox.val("");  
                //处理输入的内容自动找到下拉列表对应项  
                var retunobj = CustomEasyComBox.SelecValueEven(divComboBox, liList, ulComboBox, txtComboBox.val(), valueComboBox.val(), false);  
                //上下键滚动列表项  
                if (event.keyCode == 38 || event.keyCode == 40) {  
                    liList.removeClass("selected");  
                    liList.attr("selected", false);  
                    var indexitem = retunobj.index;  
                    //debugger  
                    switch (event.keyCode) {  
                        case 38:  //向上38  
                            indexitem = indexitem - 1;  
                            break;  
                        case 40:   // 40向下  
                            indexitem = indexitem + 1;  
                            break;  
                        default:  
                    }  
                    if (indexitem < 0) { indexitem = 0; }  
                    if (indexitem >= liList.length) { indexitem = liList.length - 1; }  
                    $(liList[indexitem]).attr({ "selected": true });  
                    $(liList[indexitem]).addClass("selected");  
                    //上下翻动时,列表滚动条跟着滚  
                    CustomEasyComBox.ScrollList(ulComboBox, $(liList[indexitem]));  
                    txtComboBox.val($(liList[indexitem]).text());  
                    valueComboBox.val($(liList[indexitem]).attr("itemvalue"));  
                    return;  
                }  
            });  
        }  
View Code

 

posted @ 2017-01-16 09:39  Adam-L  阅读(207)  评论(0)    收藏  举报