MVC 自定义分面控件
生活随笔
收集整理的這篇文章主要介紹了
MVC 自定义分面控件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;namespace System.Web.Mvc.Html
{public static class HtmlExtensions{//用 table 進行包裹/*public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string inputName, IEnumerable<SelectListItem> selectList, Position position = Position.Horizontal){return GenerateHtml(inputName, "checkbox", selectList, position);}public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Position position = Position.Horizontal){ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);string inputName = ExpressionHelper.GetExpressionText(expression);IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[inputName] as IEnumerable<SelectListItem>;IEnumerable<string> modelItems = metadata.Model as IEnumerable<string>;if (selectList == null){selectList = new List<SelectListItem>();}if (modelItems != null){selectList.ForEach(a =>{modelItems.Contains(a.Value).WhereTrue(() => a.Selected = true);});}return GenerateHtml(inputName, "checkbox", selectList, position);}public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string inputName, IEnumerable<SelectListItem> selectList, Position position = Position.Horizontal){return GenerateHtml(inputName, "radio", selectList, position);}public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Position position = Position.Horizontal){ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);//string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(inputName);string inputName = ExpressionHelper.GetExpressionText(expression);IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[inputName] as IEnumerable<SelectListItem>;if (selectList == null){selectList = new List<SelectListItem>();}if (metadata.Model != null){selectList.ForEach(a => (a.Value == metadata.Model.ToString()).WhereTrue(() => a.Selected = true));}return GenerateHtml(inputName, "radio", selectList, position);}public static MvcHtmlString GenerateHtml(string inputName, string inputType, IEnumerable<SelectListItem> selectList, Position position){TagBuilder table = new TagBuilder("table");int i = 0;if (position == Position.Horizontal){TagBuilder tr = new TagBuilder("tr");foreach (var item in selectList){i++;string inputId = string.Format("{0}_{1}", inputName, i);TagBuilder td = new TagBuilder("td");td.InnerHtml = GenerateRadioHtml(inputName, inputId, inputType, item.Value, item.Text, item.Selected);tr.InnerHtml += td.ToString();}table.InnerHtml = tr.ToString();}else{foreach (var item in selectList){TagBuilder tr = new TagBuilder("tr");i++;string inputId = string.Format("{0}_{1}", inputName, i);TagBuilder td = new TagBuilder("td");td.InnerHtml = GenerateRadioHtml(inputName, inputId, inputType, item.Value, item.Text, item.Selected);tr.InnerHtml = td.ToString();table.InnerHtml += tr.ToString();}}return new MvcHtmlString(table.ToString());}private static string GenerateRadioHtml(string inputName, string inputId, string inputType, string inputValue, string labelText, bool isChecked){StringBuilder sb = new StringBuilder();TagBuilder label = new TagBuilder("label");label.MergeAttribute("for", inputId);label.SetInnerText(labelText);TagBuilder input = new TagBuilder("input");input.GenerateId(inputId);input.MergeAttribute("name", inputName);input.MergeAttribute("type", inputType);input.MergeAttribute("value", inputValue);if (isChecked){input.MergeAttribute("checked", "checked");}sb.AppendLine(input.ToString(TagRenderMode.SelfClosing));sb.AppendLine(label.ToString());return sb.ToString();}*///生成格式 <label><input /><label> 的堆積/*public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string inputName, IEnumerable<SelectListItem> selectList){return CheckBoxList(htmlHelper, inputName, selectList, new { });}public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string inputName, IEnumerable<SelectListItem> selectList, object htmlAttributes){IDictionary<string, object> HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);HtmlAttributes.Add("type", "checkbox");HtmlAttributes.Add("name", inputName);//HtmlAttributes.Add("id", inputName);//HtmlAttributes.Add("style", "margin:0 0 0 10px;line-height:30px; vertical-align:-8px;border:none;");StringBuilder sb = new StringBuilder();foreach (SelectListItem item in selectList){IDictionary<string, object> newHtmlAttributes = HtmlAttributes.DeepCopy();newHtmlAttributes.Add("value", item.Value);newHtmlAttributes.Add("id", string.Format("{0}_{1}", inputName, item.Value));if (item.Selected){newHtmlAttributes.Add("checked", "checked");}TagBuilder input = new TagBuilder("input");input.MergeAttributes<string, object>(newHtmlAttributes);sb.AppendFormat(@"<label style=""margin:0 0 0 10px;""> {0} {1}</label>", input.ToString(TagRenderMode.SelfClosing), item.Text);}return MvcHtmlString.Create(sb.ToString());}private static IDictionary<string, object> DeepCopy(this IDictionary<string, object> ht){Dictionary<string, object> _ht = new Dictionary<string, object>();foreach (var p in ht){_ht.Add(p.Key, p.Value);}return _ht;}*///多行<div></div> 或單行 <span></span>public static MvcHtmlString RadioButtonSelectListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Position position = Position.Horizontal){ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);string inputName = ExpressionHelper.GetExpressionText(expression);IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[inputName] as IEnumerable<SelectListItem>;if (selectList == null){selectList = new List<SelectListItem>();}if (metadata.Model != null){selectList.ForEach(a => (a.Value == metadata.Model.ToString()).WhereTrue(() => a.Selected = true));}string radio = "";var sb = new StringBuilder();foreach (SelectListItem item in selectList){var inputId = string.Format("{0}_{1}", inputName, item.Value);var label = htmlHelper.Label(inputId, HttpUtility.HtmlEncode(item.Text));if (item.Selected){radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = inputId, @checked = "checked" }).ToHtmlString();}else{radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = inputId }).ToHtmlString();}sb.AppendFormat("<{2} class=\"radiobutton\">{0}{1}</{2}>", radio, label, (position == Position.Horizontal ? "span" : "div"));}return MvcHtmlString.Create(sb.ToString());}public static MvcHtmlString RadioButtonSelectList(this HtmlHelper htmlHelper, string inputName, Position position = Position.Horizontal){IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[inputName] as IEnumerable<SelectListItem>;if (selectList == null){selectList = new List<SelectListItem>();}string radio = "";StringBuilder sb = new StringBuilder();foreach (SelectListItem item in selectList){var inputId = string.Format("{0}_{1}", inputName, item.Value);var label = htmlHelper.Label(inputId, HttpUtility.HtmlEncode(item.Text));if (item.Selected){radio = htmlHelper.RadioButton(inputName, item.Value, new { id = inputId, @checked = "checked" }).ToHtmlString();}else{radio = htmlHelper.RadioButton(inputName, item.Value, new { id = inputId }).ToHtmlString();}sb.AppendFormat("<{2} class=\"radiobutton\">{0}{1}</{2}>", radio, label, (position == Position.Horizontal ? "span" : "div"));}return MvcHtmlString.Create(sb.ToString());}public static MvcHtmlString CheckBoxSelectListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Position position = Position.Horizontal){ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);string inputName = ExpressionHelper.GetExpressionText(expression);IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[inputName] as IEnumerable<SelectListItem>;IEnumerable<string> modelItems = metadata.Model as IEnumerable<string>;if (selectList == null){selectList = new List<SelectListItem>();}if (modelItems != null){selectList.ForEach(a =>{modelItems.Contains(a.Value).WhereTrue(() => a.Selected = true);});}StringBuilder stringBuilder = new StringBuilder();foreach (SelectListItem item in selectList){var inputId = string.Format("{0}_{1}", inputName, item.Value);var label = htmlHelper.Label(inputId, HttpUtility.HtmlEncode(item.Text));TagBuilder input = new TagBuilder("input");input.GenerateId(inputId);input.MergeAttribute("name", inputName);input.MergeAttribute("type", "checkbox");input.MergeAttribute("value", item.Value);if (item.Selected){input.MergeAttribute("checked", "checked");}stringBuilder.AppendFormat("<{2} class=\"checkBox\">{0}{1}</{2}>", input.ToString(TagRenderMode.SelfClosing), label, (position == Position.Horizontal ? "span" : "div"));}return MvcHtmlString.Create(stringBuilder.ToString());}public static MvcHtmlString CheckBoxSelectList(this HtmlHelper htmlHelper, string inputName, Position position = Position.Horizontal){IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[inputName] as IEnumerable<SelectListItem>;if (selectList == null){selectList = new List<SelectListItem>();}StringBuilder sb = new StringBuilder();foreach (SelectListItem item in selectList){var inputId = string.Format("{0}_{1}", inputName, item.Value);var label = htmlHelper.Label(inputId, HttpUtility.HtmlEncode(item.Text));TagBuilder input = new TagBuilder("input");input.GenerateId(inputId);input.MergeAttribute("name", inputName);input.MergeAttribute("type", "checkbox");input.MergeAttribute("value", item.Value);if (item.Selected){input.MergeAttribute("checked", "checked");}sb.AppendFormat("<{2} class=\"checkBox\">{0}{1}</{2}>", input.ToString(TagRenderMode.SelfClosing), label, (position == Position.Horizontal ? "span" : "div"));}return MvcHtmlString.Create(sb.ToString());}public static MvcHtmlString CheckBoxSelectList(this HtmlHelper htmlHelper, string inputName, IEnumerable<SelectListItem> selectList, Position position = Position.Horizontal){if (selectList == null){selectList = new List<SelectListItem>();}StringBuilder sb = new StringBuilder();foreach (SelectListItem item in selectList){var inputId = string.Format("{0}_{1}", inputName, item.Value);var label = htmlHelper.Label(inputId, HttpUtility.HtmlEncode(item.Text));TagBuilder input = new TagBuilder("input");input.GenerateId(inputId);input.MergeAttribute("name", inputName);input.MergeAttribute("type", "checkbox");input.MergeAttribute("value", item.Value);if (item.Selected){input.MergeAttribute("checked", "checked");}sb.AppendFormat("<{2} class=\"checkBox\">{0}{1}</{2}>", input.ToString(TagRenderMode.SelfClosing), label, (position == Position.Horizontal ? "span" : "div"));}return MvcHtmlString.Create(sb.ToString());}public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression){string selectName = ExpressionHelper.GetExpressionText(expression);string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(selectName);IEnumerable<SelectListItem> selectList = htmlHelper.ViewData[selectName] as IEnumerable<SelectListItem>;IEnumerable<SelectListItem> selectList2 = htmlHelper.ViewData.Eval(selectName) as IEnumerable<SelectListItem>;IEnumerable<string> modelItems = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model as IEnumerable<string>;if (selectList == null){selectList = new List<SelectListItem>();}if (modelItems != null){selectList.ForEach(a =>{modelItems.Contains(a.Value).WhereTrue(() => a.Selected = true);});}StringBuilder listItemBuilder = new StringBuilder();foreach (SelectListItem item in selectList){listItemBuilder.AppendLine(ListItemToOption(item));}TagBuilder tagBuilder = new TagBuilder("select"){InnerHtml = listItemBuilder.ToString()};tagBuilder.MergeAttribute("name", fullName, true);tagBuilder.GenerateId(fullName);return MvcHtmlString.Create(tagBuilder.ToString());}internal static string ListItemToOption(SelectListItem item){TagBuilder builder = new TagBuilder("option"){InnerHtml = HttpUtility.HtmlEncode(item.Text)};if (item.Value != null){builder.Attributes["value"] = item.Value;}if (item.Selected){builder.Attributes["selected"] = "selected";}return builder.ToString(TagRenderMode.Normal);}}#region - 指定列表控件項的顯示方向 -/// <summary>/// 指定列表控件項的顯示方向。/// </summary>public enum Position{/// <summary>/// 列表項以行的形式水平顯示,從左到右、自上而下地加載,直到呈現出所有的項。/// </summary>Horizontal = 0,/// <summary>/// 列表項以列的形式垂直顯示,自上而下、從左到右地加載,直到呈現出所有的項。/// </summary>Vertical = 1,}#endregion
}
using System.Text;namespace System.Web.Mvc.Html {public static class HtmlHelperExtensions{public static HtmlString SimplePagination(this HtmlHelper htmlHelper, int pageIndex, int pageSize, int totalCount, object queryString = null){var strQueryString = queryString.GetQueryString();pageSize = pageSize <= 0 ? 3 : pageSize;var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //總頁數var output = new StringBuilder();if (totalPages > 1){var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;if (pageIndex > 1){//處理首頁連接output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}{2}'>首頁</a> ", redirectTo, pageSize, strQueryString);}else{output.Append("<a class='pageLink' href='javascript:;' style='cursor:default'>首頁</a> ");}if (pageIndex > 1){//處理上一頁的連接output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>上一頁</a> ", redirectTo, pageIndex - 1, pageSize, strQueryString);}else{output.Append("<a class='pageLink' href='javascript:;' style='cursor:default'>上一頁</a> ");}int intervalInt = 5;int begin = Math.Max((pageIndex - intervalInt), 1);//int end = Math.Min(totalPages, begin + (intervalInt * 2));int end = Math.Min(totalPages, ((intervalInt * 2) + (pageIndex - intervalInt)));for (int i = begin; i <= end; i++){if (i == pageIndex){//當前頁處理output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}{3}'>{4}</a> ", redirectTo, pageIndex, pageSize, strQueryString, pageIndex);}else{//一般頁處理output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>{4}</a> ", redirectTo, i, pageSize, strQueryString, i);}}if (pageIndex < totalPages){//處理下一頁的鏈接output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>下一頁</a> ", redirectTo, pageIndex + 1, pageSize, strQueryString);}else{output.Append("<a class='pageLink' href='javascript:;' style='cursor:default'>下一頁</a> ");}if (pageIndex < totalPages){output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}{3}'>尾頁</a> ", redirectTo, totalPages, pageSize, strQueryString);}else{output.Append("<a class='pageLink' href='javascript:;' style='cursor:default'>尾頁</a>");}}output.AppendFormat("<a class='pageLink' href='javascript:;' style='cursor:default'>第{0}頁 / 共{1}頁</a>", pageIndex, totalPages);//這個統計加不加都行return new HtmlString(output.ToString());}public static string GetQueryString(this object queryString){if (queryString == null){return "";}Type type = queryString.GetType();var sb = new StringBuilder();foreach (var item in type.GetProperties()){sb.AppendFormat("&{0}={1}", item.Name, item.GetValue(queryString, null));}return sb.ToString();}public static string GetHtmlAttributes(object htmlAttributes){if (htmlAttributes == null){return "";}Type type = htmlAttributes.GetType();var sb = new StringBuilder();foreach (var item in type.GetProperties()){sb.AppendFormat("{0}=\"{1}\" ", item.Name, item.GetValue(htmlAttributes, null));}return sb.ToString();}} }
using System.Linq.Expressions;namespace System.Web.Mvc.Html {public static class DisplayDescriptionExtensions{#region - DisplayDescription -/// <summary>/// 模型描述信息/// </summary>/// <param name="htmlHelper"></param>/// <param name="name"></param>/// <returns></returns>public static MvcHtmlString DisplayDescription(this HtmlHelper htmlHelper, string name){ModelMetadata modelMetadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewData);return MvcHtmlString.Create(modelMetadata.Description);}/// <summary>/// 模型描述信息/// </summary>/// <typeparam name="TModel"></typeparam>/// <typeparam name="TResult"></typeparam>/// <param name="htmlHelper"></param>/// <param name="expression"></param>/// <returns></returns>public static MvcHtmlString DisplayDescriptionFor<TModel, TResult>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression){ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);return MvcHtmlString.Create(modelMetadata.Description);}#endregion} }
轉載于:https://www.cnblogs.com/leonGuo/archive/2013/03/22/2976068.html
總結
以上是生活随笔為你收集整理的MVC 自定义分面控件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分享:When.js 2.0.0 发布,
- 下一篇: 稳定多维table排序