基于JQuery EasyUI的WebMVC控件封装(含源码)

  JQuery EasyUI类库,大家不会陌生,出来已经有很多年了。个人感觉还是很好用的,作者更新频率也很快,bug也及时修复。

  最近在整理以前的代码,找到了这个组件,它是将EasyUI组件封装成MVC控件,这样我们就可以不用写那些html标签了,我们先看看调用方式

<form id="form1">
    @Html.HiddenFor(c => c.ID)
    @Html.HiddenFor(c => c.EditMode)
    @Html.HiddenFor(c => c.CodeTypeID)
    @Html.HiddenFor(c => c.CreateUserID)
    <table border="1" style="width: 100%;">
        <tr>
            <td style="width: 100px;">@Html.EasyUI().LabelFor(c => c.CodeID).Required(true)</td>
            <td>@Html.EasyUI().ValidateBoxFor(c => c.CodeID).Required(true).Width("60%")</td>
        </tr>
        <tr>
            <td>@Html.EasyUI().LabelFor(c => c.CodeName).Required(true)</td>
            <td>@Html.EasyUI().ValidateBoxFor(c => c.CodeName).Required(true).Width("60%")</td>
        </tr>
        <tr>
            <td>@Html.EasyUI().LabelFor(c => c.CodeTypeName)</td>
            <td>@Html.DisplayFor(c => c.CodeTypeName)</td>
        </tr>
        <tr>
            <td>@Html.EasyUI().LabelFor(c => c.IsUsed)</td>
            <td>@Html.DropDownListMetaCodeFor(c => c.IsUsed, MetaSourceType.Null, string.Empty, new{ @style = "width:60%;" })</td>
        </tr>
        <tr>
            <td>@Html.EasyUI().LabelFor(c => c.SortOrder)</td>
            <td>@Html.EasyUI().NumberBoxFor(c => c.SortOrder).Min(10).Value(10).Width("60%")</td>
        </tr>
        <tr>
            <td>@Html.EasyUI().LabelFor(c => c.CreateUserName)</td>
            <td>@Html.EasyUI().ValidateBoxFor(c => c.CreateUserName).Width("60%")</td>
        </tr>
        <tr>
            <td>@Html.EasyUI().LabelFor(c => c.CreateTime)</td>
            <td>@Html.EasyUI().DateBoxFor(c => c.CreateTime)</td>
        </tr>
    </table>
</form>

  我们再来看看代码是如何实现的,下面是整个项目布局

  其实代码不复杂,最关键的是TagElementBuilder.cs这个类

using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NS.Utility.EasyUI
{
    public abstract class TagElementBuilder<T> : IHtmlString where T : class
    {
        #region 私有变量
        private TagBuilder tagBuilder;
        #endregion

        #region 公有属性
        /// <summary>
        /// 组件Tag标签类型.包括input,select,label等
        /// </summary>
        public abstract string TagName { get; }

        /// <summary>
        /// Tag标签组装类
        /// </summary>
        protected TagBuilder TagBuilder
        {
            get
            {
                if (this.tagBuilder != null)
                    return this.tagBuilder;
                return this.tagBuilder = new TagBuilder(TagName);
            }
        }          
        #endregion

        #region 私有方法
        /// <summary>
        /// 判断class名称是否存在
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        private bool ContainsClass(string className)
        {
            string classs;
            if (!TagBuilder.Attributes.TryGetValue("class", out classs))
            {
                return false;
            }

            var classArray = classs.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
            return classArray.Any(i => string.Equals(i, className, StringComparison.OrdinalIgnoreCase));
        }
        #endregion

        #region 公有方法

        /// <summary>
        /// 设置ID属性值
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T ID(string id)
        {
            this.TagBuilder.GenerateId(id);
            return this as T;
        }

        /// <summary>
        /// 设置Name属性值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public T Name(string name)
        {
            this.TagBuilder.MergeAttribute("name", name, true);
            return this as T;
        }

        /// <summary>
        /// 设置Attribute属性列表
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="replaceExisting"></param>
        /// <returns></returns>
        public T Attribute(string key, string value, bool replaceExisting = false)
        {
            this.TagBuilder.MergeAttribute(key, value, replaceExisting);
            return this as T;
        }

        /// <summary>
        /// 增加class属性值
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public T AddClass(string className)
        {
            if (string.IsNullOrWhiteSpace(className))
            {
                return this as T;
            }

            if (ContainsClass(className))
            {
                return this as T;
            }

            TagBuilder.AddCssClass(className);
            return this as T;
        }

        /// <summary>
        /// 删除class属性值
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public T RemoveClass(string className)
        {
            if (string.IsNullOrWhiteSpace(className))
            {
                return this as T;
            }

            if (!ContainsClass(className))
            {
                return this as T;
            }

            var classs = TagBuilder.Attributes["class"];

            var classArray = classs.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Where(i => string.Equals(i, className, StringComparison.OrdinalIgnoreCase));

            TagBuilder.Attributes["class"] = string.Join(" ", classArray);
            return this as T;
        }

        /// <summary>
        /// 合并class属性值
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public T ToggleClass(string className)
        {
            if (string.IsNullOrWhiteSpace(className))
            {
                return this as T;
            }

            return ContainsClass(className) ? RemoveClass(className) : AddClass(className);
        }
        #endregion

        #region 抽象方法
        /// <summary>
        /// 返回HTML编码的字符串(子类必须重写)
        /// </summary>
        /// <returns></returns>
        public abstract string ToHtmlString();
        #endregion
    }
}

  再看看具体是如何实现的?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace NS.Utility.EasyUI
{
    public class ComboBoxBuilder : TagElementBuilder<ComboBoxBuilder>
    {
        #region 私有变量
        private bool required = false;
        private string valueField = string.Empty;
        private string textField = string.Empty;
        private string groupField = string.Empty;
        private string groupFormatter = string.Empty;
        private EasyUIComboBoxMode mode = EasyUIComboBoxMode.local;
        private string url = string.Empty;
        private EasyUIComboBoxMethod method = EasyUIComboBoxMethod.post;
        private string data = string.Empty;
        private string filter = string.Empty;
        private string formatter = string.Empty;
        private string loader = string.Empty;
        private string loadFilter = string.Empty;

        private string onBeforeLoad = string.Empty;
        private string onLoadSuccess = string.Empty;
        private string onLoadError = string.Empty;
        private string onSelect = string.Empty;
        private string onUnselect = string.Empty;
        #endregion

        #region 公有方法
        public ComboBoxBuilder Required(bool required)
        {
            this.required = required;
            return this;
        }
        public ComboBoxBuilder ValueField(string valueField)
        {
            this.valueField = valueField;
            return this;
        }
        public ComboBoxBuilder TextField(string textField)
        {
            this.textField = textField;
            return this;
        }
        public ComboBoxBuilder GroupField(string groupField)
        {
            this.groupField = groupField;
            return this;
        }
        public ComboBoxBuilder GroupFormatter(string groupFormatter)
        {
            this.groupFormatter = groupFormatter;
            return this;
        }
        public ComboBoxBuilder Mode(EasyUIComboBoxMode mode)
        {
            this.mode = mode;
            return this;
        }
        public ComboBoxBuilder Url(string url)
        {
            this.url = url;
            return this;
        }
        public ComboBoxBuilder Method(EasyUIComboBoxMethod method)
        {
            this.method = method;
            return this;
        }
        public ComboBoxBuilder Data(string data)
        {
            this.data = data;
            return this;
        }
        public ComboBoxBuilder Filter(string filter)
        {
            this.filter = filter;
            return this;
        }
        public ComboBoxBuilder Formatter(string formatter)
        {
            this.formatter = formatter;
            return this;
        }
        public ComboBoxBuilder Loader(string loader)
        {
            this.loader = loader;
            return this;
        }
        public ComboBoxBuilder LoadFilter(string loadFilter)
        {
            this.loadFilter = loadFilter;
            return this;
        }

        public ComboBoxBuilder OnBeforeLoad(string onBeforeLoad)
        {
            this.onBeforeLoad = onBeforeLoad;
            return this;
        }
        public ComboBoxBuilder OnLoadSuccess(string onLoadSuccess)
        {
            this.onLoadSuccess = onLoadSuccess;
            return this;
        }
        public ComboBoxBuilder OnLoadError(string onLoadError)
        {
            this.onLoadError = onLoadError;
            return this;
        }
        public ComboBoxBuilder OnSelect(string onSelect)
        {
            this.onSelect = onSelect;
            return this;
        }
        public ComboBoxBuilder OnUnselect(string onUnselect)
        {
            this.onUnselect = onUnselect;
            return this;
        }
        #endregion

        #region TagElementBuilder 重写属性和方法
        public override string TagName
        {
            get { return "input"; }
        }

        public override string ToHtmlString()
        {
            //参考格式:<input id="cc" class="easyui-combobox" name="dept" data-options="valueField:'id',textField:'text',url:'get_data.php'" /> 

            //拼接class属性值
            TagBuilder.AddCssClass("easyui-combobox");

            //拼接data-options属性值
            List<string> listAttri = new List<string>();

            //开始拼接各种属性值
            if (this.required == true)
            {
                //是否必输项
                listAttri.Add(string.Format("required:{0}", this.required.ToString().ToLower()));
            }
            if (string.IsNullOrEmpty(this.valueField) == false)
            {
                listAttri.Add(string.Format("valueField:'{0}'", this.valueField));
            }
            if (string.IsNullOrEmpty(this.textField) == false)
            {
                listAttri.Add(string.Format("textField:'{0}'", this.textField));
            }
            if (string.IsNullOrEmpty(this.groupField) == false)
            {
            }
            if (this.mode != EasyUIComboBoxMode.local)
            {
            }
            if (string.IsNullOrEmpty(this.url) == false)
            {
                listAttri.Add(string.Format("url:'{0}'", this.url));
            }
            if (this.method == EasyUIComboBoxMethod.get)
            {
            }
            if (string.IsNullOrEmpty(this.data) == false)
            {
            }
            if (string.IsNullOrEmpty(this.filter) == false)
            {
            }
            if (string.IsNullOrEmpty(this.formatter) == false)
            {
            }
            if (string.IsNullOrEmpty(this.loader) == false)
            {         
            }
            if (string.IsNullOrEmpty(this.loadFilter) == false)
            {
            }

            //开始拼接各种事件
            if (string.IsNullOrEmpty(this.onBeforeLoad) == false)
            {
            }
            if (string.IsNullOrEmpty(this.onLoadSuccess) == false)
            {
            }
            if (string.IsNullOrEmpty(this.onLoadError) == false)
            {
            }
            if (string.IsNullOrEmpty(this.onSelect) == false)
            {
            }
            if (string.IsNullOrEmpty(this.onUnselect) == false)
            {
            }

            string dataOptions = string.Join(",", listAttri.ToArray());
            TagBuilder.Attributes.Add("data-options", dataOptions);

            var builder = new StringBuilder();
            var tagHtml = TagBuilder.ToString(TagRenderMode.SelfClosing);
            builder.AppendLine(tagHtml);

            return new MvcHtmlString(builder.ToString()).ToHtmlString();
        }
        #endregion
    }
}

  看,其实并不复杂吧,完整源码是必须提供的

源码下载方式 1,关注微信公众号:小特工作室(也可直接扫描签名处二维码) 2,发送:示例4011 即可下载 

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏菩提树下的杨过

Flash/Flex学习笔记(32):播放音乐并同步显示lyc歌词(适用于Silverlight)

题外话:个别朋友总是问我同样的问题,做为一名c#/silverlight程序员为啥还要学flash ? 回 答:看日本片时,就不能对照看欧美的么? 不体会日本的...

22370
来自专栏技术之路

WPF之TreeList的实现方法(一)

做项目的时候根据需求,WPF现有的控件不能完全满足我们的需求, 很多时候我们需要对现有的控件做一下加工。 最简单的我们可能会把Tree转换成List形式有的叫G...

27350
来自专栏跟着阿笨一起玩NET

NPOI简述与运用

最近想把项目中Excel中的操作部分改成NPOI ,由于2.0版本已经支持office07/10格式,但还处于测试版不稳定,于是封装如下代码

14710
来自专栏谈补锅

记录C#常用的代码片段

using Newtonsoft.Json; using Newtonsoft.Json.Linq;

22620
来自专栏腾讯云技术服务团队

C#封装v5 COS API实践-put方法

16030
来自专栏函数式编程语言及工具

Akka(37): Http:客户端操作模式

   Akka-http的客户端连接模式除Connection-Level和Host-Level之外还有一种非常便利的模式:Request-Level-Api。...

39770
来自专栏电光石火

C#解析JSON

使用开源的类库Newtonsoft.Json(下载地址http://json.codeplex.com/)。下载后添加dll引用就能用。 首先添加引用:usin...

31290
来自专栏JadePeng的技术博客

使用Mongodb 做对象缓存

mongodb高效的访问速度,用来快速存取数据再合适不过了,缓存神马的,可以用这个的 另外,有的时候,如果仅仅存储几条数据,单独去建立一张表代价太大,这个时候,...

51050
来自专栏电光石火

C#解析JSON

使用开源的类库Newtonsoft.Json(下载地址http://json.codeplex.com/)。下载后添加dll引用就能用。 首先添加引用:us...

69250
来自专栏张善友的专栏

ASP.NET MVC Preview生命周期分析

做ASP.NET WebForm开发都知道,ASP.NET有复杂的生命周期,学习ASP.NET MVC就要深入理解它的生命周期。今天从CodePlex上下载了A...

22370

扫码关注云+社区

领取腾讯云代金券