wyb
2021-05-11 49ce087bd2a34a150597e1cc1da157af242c0b6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
 
using System.Xml.Linq;
using System.ComponentModel.DataAnnotations;
using Pcb.Domain.DataAnnotationsAttribute;
 
namespace Pcb.Common.Utilities
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString GetSubString(this HtmlHelper helper, string str, int n)
        {
            return MvcHtmlString.Create(HtmlHelpers.GetSubString(str, n));
        }
 
        public static MvcHtmlString Summary(this HtmlHelper helper, string str, int n)
        {
            str = HtmlHelpers.StripTagsRegex(str);
            return MvcHtmlString.Create(HtmlHelpers.GetSubString(str, n));
        }
 
        private static string StripTagsRegex(string source)
        {
            return Regex.Replace(source, "<.*?>", string.Empty);
        }
 
        private static string GetSubString(string str, int n)
        {
            string temp = string.Empty;
            if (System.Text.Encoding.Default.GetByteCount(str) <= n)//如果长度比需要的长度n小,返回原字符串  
            {
                return str;
            }
            else
            {
                int t = 0;
                char[] q = str.ToCharArray();
                for (int i = 0; i < q.Length; i++)
                {
                    if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5)//是否汉字  
                    {
                        temp += q[i];
                        t += 2;
                    }
                    else
                    {
                        temp += q[i];
                        t += 1;
                    }
                    if (t >= n)
                    {
                        return (temp + "...");
                    }
                }
                return temp;
            }
        }
 
        /// <summary>
        /// 创建分页链接
        /// </summary>
        /// <param name="helper">HtmlHelper类</param>
        /// <param name="startPage">开始页 (多数情况下是 1)</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="totalPages">总页数</param>
        /// <param name="pagesToShow">前后显示的页数</param>
        public static MvcHtmlString Pager(this HtmlHelper helper, int startPage, int currentPage, int totalPages, int pagesToShow)
        {
            RouteData routeData = helper.ViewContext.RouteData;
            //你可能还要获取action
            string action = routeData.Values["action"].ToString();
            string controller = routeData.Values["controller"].ToString();
            StringBuilder html = new StringBuilder();
            //创建从第一页到最后一页的列表
            html = Enumerable.Range(startPage, totalPages)
            .Where(i => (currentPage - pagesToShow) < i & i < (currentPage + pagesToShow))
            .Aggregate(new StringBuilder(@"<div class=""pagination""><span class=""total"">共" + totalPages + "页</span>"), (seed, page) =>
            {
                //当前页
                if (page == currentPage)
                {
                    seed.AppendFormat("<span class=\"current\">{0}</span>", page);
                }
                else
                {
                    //第一页时显示:domain/archives
                    UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
 
                    NameValueCollection col = helper.ViewContext.RequestContext.HttpContext.Request.QueryString;
                    var values = new RouteValueDictionary(new { p = page });
                    if (col != null)
                    {
                        foreach (string key in col)
                        {
                            //values passed in object override those already in collection
                            if (!values.ContainsKey(key)) values[key] = col[key];
                        }
                    }
                    seed.AppendFormat("<a href=\"{0}\">{1}</a>", url.Action(action, controller, values), page);
                }
                return seed;
            });
            html.Append(@"</div>");
            return MvcHtmlString.Create(html.ToString());
        }
 
        //public static MvcHtmlString OrderStatusFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        //{
        //    MvcHtmlString str = html.DisplayFor(expression);
        //    string test = str.ToString();
        //    SelectListItem item = Orders.AllPaymentStatus.Single(m => m.Value.Equals(test) == true);
 
        //    return MvcHtmlString.Create(item.Text);
 
        //}
 
        //public static MvcHtmlString PaymentGatewayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        //{
        //    MvcHtmlString str = html.DisplayFor(expression);
        //    string test = str.ToString();
        //    if (test != null && test.Length > 0)
        //    {
        //        SelectListItem item = Orders.AllPaymentGateway.Single(m => m.Value.Equals(test) == true);
        //        return MvcHtmlString.Create(item.Text);
        //    }
        //    return MvcHtmlString.Create("");
 
        //}
 
 
        public static MvcHtmlString YNStatus<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            MvcHtmlString str = html.DisplayFor(expression);
 
            StringBuilder sb = new StringBuilder();
            switch (str.ToString())
            {
                case "0":
                    sb.Append("否");
                    break;
                default:
                    sb.Append("是");
                    break;
            }
            return MvcHtmlString.Create(sb.ToString());
        }
 
        public static MvcHtmlString SnStatus<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            MvcHtmlString str = html.DisplayFor(expression);
 
            StringBuilder sb = new StringBuilder();
            switch (str.ToString())
            {
                case "0":
                    sb.Append("无效");
                    break;
                case "1":
                    sb.Append("有效");
                    break;
            }
            return MvcHtmlString.Create(sb.ToString());
        }
 
        public static MvcHtmlString MemberTypeFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            MvcHtmlString str = html.DisplayFor(expression);
 
            StringBuilder sb = new StringBuilder();
            switch (str.ToString())
            {
                case "Staff":
                    sb.Append("内部员工");
                    break;
                case "Star3":
                    sb.Append("三星代理");
                    break;
                case "Star4":
                    sb.Append("四星代理");
                    break;
                case "Star5":
                    sb.Append("五星代理");
                    break;
                case "Members":
                    sb.Append("普通会员");
                    break;
                default:
                    sb.Append(str);
                    break;
 
            }
            return MvcHtmlString.Create(sb.ToString());
        }
 
        //public static MvcHtmlString MemberByUid(this HtmlHelper helper, Guid uid)
        //{
        //    PortalSitesEntities db = new PortalSitesEntities();
        //    StringBuilder sb = new StringBuilder();
        //    Members Members = db.Members.SingleOrDefault(m => m.Uid == uid);
        //    if (null != Members)
        //    {
        //        sb.Append(Members.UserName);
        //    }
 
        //    return MvcHtmlString.Create(sb.ToString());
        //}
 
        //public static MvcHtmlString Block(this HtmlHelper helper, string code)
        //{
        //    PortalSitesEntities db = new PortalSitesEntities();
 
        //    Blocks block = db.Blocks.SingleOrDefault(m => m.Code == code);
        //    if (null != block)
        //    {
        //        return MvcHtmlString.Create(block.Content);
        //    }
        //    else
        //    {
        //        return MvcHtmlString.Create("{" + code + "}");
        //    }
        //}
 
        //public static MvcHtmlString WxJsConfig(this HtmlHelper helper)
        //{
        //    int platId = MyCore.plat;
        //    Entity.ViewModel.ClientCredentialEntity credential = new ClientCredentialBll().GetClientCredentialEntityByWeixinID(platId);
        //    string ticket = new ClientCredentialBll().GetJsapiTicket(platId);
        //    string nonceStr = Common.RandomHelper.GetRandomString(16, true, true, true, false, "");
        //    DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        //    string timestamp = "" + (int)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
        //    string url = HttpContext.Current.Request.Url.AbsoluteUri;
        //    string rawString = String.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket, nonceStr, timestamp, url);
        //    string signature = CommonMd5.SHA1_Encrypt(rawString);
 
        //    StringBuilder output = new StringBuilder();
        //    output.Append("wx.config({");
        //    output.Append(" debug: false,");
        //    output.AppendFormat(" appId: '{0}',", credential.AppId);
        //    output.AppendFormat(" timestamp: '{0}',", timestamp);
        //    output.AppendFormat(" nonceStr: '{0}',", nonceStr);
        //    output.AppendFormat(" signature: '{0}',", signature);
        //    output.Append(" jsApiList:  ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems','showMenuItems','chooseWXPay']");
        //    output.Append("});");
 
        //    return MvcHtmlString.Create(output.ToString()); ;
        //}
 
 
        //public static MvcHtmlString QuesOptionsFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
        //{
        //    StringBuilder output = new StringBuilder();
        //    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        //    Object obj = helper.ViewData.Model;
        //    String name = metadata.PropertyName;
 
        //    MetadataTypeAttribute[] metadataTypes = obj.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().ToArray();
        //    MetadataTypeAttribute metadatas = metadataTypes.FirstOrDefault();
        //    if (metadatas != null)
        //    {
        //        PropertyInfo[] properties = metadatas.MetadataClassType.GetProperties();
 
        //        PropertyInfo field222 = properties.Where(t => t.Name == name).FirstOrDefault();
        //        //QuesOptionsAttribute options = ((QuesOptionsAttribute[])field222.GetCustomAttributes(typeof(QuesOptionsAttribute), false)).FirstOrDefault();
 
 
 
 
        //        //PropertyInfo field = obj.GetType().GetProperty(name);
        //        //QuesOptionsAttribute options = ((QuesOptionsAttribute[])field.GetCustomAttributes(typeof(QuesOptionsAttribute), false)).FirstOrDefault();
        //        if (null == options)
        //        {
        //            return MvcHtmlString.Empty;
        //        }
        //        string[] opts = options.Options.Split(',');
 
 
 
        //        foreach (string opt in opts)
        //        {
        //            output.Append("<label>");
        //            output.Append(helper.RadioButtonFor(expression, opt.Trim()));
        //            output.Append(opt.Trim());
        //            output.Append("</label>  ");
        //        }
        //    }
        //    return MvcHtmlString.Create(output.ToString());
        //}
 
        //public static MvcHtmlString QuesCheckedOptionsFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
        //{
        //    StringBuilder output = new StringBuilder();
        //    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        //    Object obj = helper.ViewData.Model;
        //    String name = metadata.PropertyName;
 
        //    MetadataTypeAttribute[] metadataTypes = obj.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().ToArray();
        //    MetadataTypeAttribute metadatas = metadataTypes.FirstOrDefault();
        //    if (metadatas != null)
        //    {
        //        PropertyInfo[] properties = metadatas.MetadataClassType.GetProperties();
 
        //        PropertyInfo field222 = properties.Where(t => t.Name == name).FirstOrDefault();
        //        QuesOptionsAttribute options = ((QuesOptionsAttribute[])field222.GetCustomAttributes(typeof(QuesOptionsAttribute), false)).FirstOrDefault();
 
 
 
 
        //        //PropertyInfo field = obj.GetType().GetProperty(name);
        //        //QuesOptionsAttribute options = ((QuesOptionsAttribute[])field.GetCustomAttributes(typeof(QuesOptionsAttribute), false)).FirstOrDefault();
        //        if (null == options)
        //        {
        //            return MvcHtmlString.Empty;
        //        }
        //        string[] opts = options.Options.Split(',');
 
 
 
        //        foreach (string opt in opts)
        //        {
        //            output.Append("<label>");
 
        //            output.Append(" <input type=\"checkbox\" name=\"" + name + "\"  value=\"" + opt.Trim() + "\" />" + opt.Trim());
 
        //            output.Append("</label>  ");
        //        }
        //    }
        //    return MvcHtmlString.Create(output.ToString());
        //}
 
        public static MvcHtmlString CalenderTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
        {
            var mvcHtmlString = InputExtensions.TextBoxFor(htmlHelper, expression, htmlAttributes ?? new { @class = "text-box single-line date-picker" });
            var xDoc = XDocument.Parse(mvcHtmlString.ToHtmlString());
            var xElement = xDoc.Element("input");
            if (xElement != null)
            {
                var valueAttribute = xElement.Attribute("value");
                if (valueAttribute != null)
                {
                    valueAttribute.Value = DateTime.Parse(valueAttribute.Value).ToShortDateString();
                    if (valueAttribute.Value == "1/1/0001")
                        valueAttribute.Value = string.Empty;
                }
            }
            return new MvcHtmlString(xDoc.ToString());
        }
 
 
    }
 
}