Files
zszq-trs/YLErpWeb/Common/MyHelper.cs
T
2024-05-09 14:06:26 +08:00

910 lines
45 KiB
C#

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.RegularExpressions;
namespace YLErp.Web
{
/// <summary>
///
/// </summary>
public static class FormExtensions
{
private static string FormatDate(DateTime? d)
{
return d == null ? string.Empty : ((DateTime)d).ToString("yyyy-MM-dd");
}
private static string ToHtmlString(IHtmlContent content)
{
using (var writer = new StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
private static ModelExpression GetModelExpression<TModel, TValue>(IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
var expressionProvider = helper.ViewContext.HttpContext.RequestServices
.GetService(typeof(ModelExpressionProvider)) as ModelExpressionProvider;
return expressionProvider.CreateModelExpression(helper.ViewData, expression);
}
public static IHtmlContent MyDisplayFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string text)
{
var displayName = helper.DisplayNameFor(expression);
return new HtmlString(string.Format("<th class='tdRight'>{0}</th><td>{1}</td>", displayName, text));
}
public static IHtmlContent MyDisplayFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
return MyDisplayFor(helper, expression, false);
}
public static IHtmlContent MyDisplayFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool isRaw)
{
var modelExpression = GetModelExpression(helper, expression);
var text = "";
var valueType = typeof(TValue);
if (modelExpression.Model is null)
{
}
else if (valueType == typeof(DateTime))
{
if (modelExpression.Metadata.PropertyName.Contains("Time"))
{
text = ((DateTime)modelExpression.Model).ToString("yyyy/MM/dd HH:mm");
}
else
{
text = FormatDate((DateTime)modelExpression.Model);
}
}
else if (valueType == typeof(DateTime?))
{
if (modelExpression.Metadata.PropertyName.Contains("Time"))
{
text = ((DateTime?)modelExpression.Model).Value.ToString("yyyy/MM/dd HH:mm");
}
else
{
text = FormatDate((DateTime?)modelExpression.Model);
}
}
else if (valueType == typeof(bool))
{
text = ((bool)modelExpression.Model) ? "是" : "否";
}
else if (valueType == typeof(bool?))
{
text = ((bool?)modelExpression.Model).Value ? "是" : "否";
}
else
{
text = helper.ValueFor(expression);
}
var displayName = helper.DisplayNameFor(expression);
if (isRaw)
{
return new HtmlString(string.Format("<th class='tdRight'>{0}</th><td>{1}</td>", displayName, helper.Raw(text)));
}
else
{
return new HtmlString(string.Format("<th class='tdRight'>{0}</th><td>{1}</td>", displayName, helper.Encode(text).Replace("\n", "<br/>")));
}
}
public static IHtmlContent MyAceDropdownFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
List<SelectItem> list, string defaultValue = "", bool appendBlank = true, bool showRequired = false, string layoutClass = "col-md-6", string placeholder = null)
{
return MyAceDropdownFor(helper, expression, list.Select(HtmlExtensions.AsSelectListItem).ToList(), defaultValue, appendBlank, showRequired, layoutClass, placeholder);
}
public static IHtmlContent MyAceDropdownFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
List<SelectListItem> list, string defaultValue = "", bool appendBlank = true, bool showRequired = false, string layoutClass = "col-md-6", string placeholder = null)
{
if (appendBlank == true)
{
if (list.Count == 0 || list.Count > 0 && list[0].Value != "")
{
list.Insert(0, new SelectListItem() { Value = "", Text = "----" });
}
}
var modelExpression = GetModelExpression(helper, expression);
var dValue = defaultValue;
var needReplaceString = new List<string>();
if (!string.IsNullOrEmpty(defaultValue))
{
foreach (var selectListItem in list)
{
if (selectListItem.Value == defaultValue)
{
selectListItem.Selected = true;
}
}
}
else if (!string.IsNullOrEmpty(modelExpression.Model + ""))
{
dValue = modelExpression.Model + "";
var selectValues = dValue.Split(","[0]).ToList();
foreach (var sel in selectValues)
{
if (string.IsNullOrEmpty(sel))
{
continue;
}
needReplaceString.Add(string.Format("value=\"{0}\"", sel));
foreach (var selectListItem in list)
{
if (selectListItem.Value == sel + "")
{
selectListItem.Selected = true;
}
}
}
}
var m3 = helper.ValidationMessageFor(expression);
///0,1,2,3ddlstring
var str = "<div class='form-group {5}'><label class='formlabel' for='{0}'>{1}</label>{2} {3} {4}</div>";
var m2 = helper.DropDownList(modelExpression.Name, list, new { @class = "chosen-select", data_placeholder = placeholder != null ? placeholder : "请选择 ", multiple = "" });
var m2FilterString = ToHtmlString(m2);
needReplaceString.ForEach(r => m2FilterString = m2FilterString.Replace(r, r + " selected=\"selected\" "));
var displayName = helper.DisplayNameFor(expression);
var fullStr = string.Format(str, modelExpression.Name, displayName, m2FilterString
, showRequired || modelExpression.Metadata.IsRequired ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3), layoutClass);
return new HtmlString(fullStr);
}
public static IHtmlContent MyCheckBoxFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool required = false)
{
var modelExpression = GetModelExpression(helper, expression);
var str = @"
<div class='form-group col-md-6'>
<label class='formlabel' for='{0}'>{1}</label>
<input id='{0}' class='form-checkbox' type='checkbox' {2} name='{0}'{3} />{4} {5}
</div>";
var _required = modelExpression.Metadata.IsRequired || required;
bool.TryParse(modelExpression.Model + "", out var ischecked);
var m3 = helper.ValidationMessageFor(expression);
var displayName = helper.DisplayNameFor(expression);
var fullStr = string.Format(str, modelExpression.Name,
displayName,
ischecked ? "checked='checked'" : "",
_required ? string.Format(" data-val='true' data-val-required='{0} 字段是必需的'", displayName) : "",
_required ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3));
return new HtmlString(fullStr);
}
public static IHtmlContent MyDecimalFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool required = false)
{
return MyDecimalFor(helper, expression, null, required);
}
/// <summary>
///
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="helper"></param>
/// <param name="expression"></param>
/// <param name="htmlAttributes">html属性赋值,例如:new{value="11"}</param>
/// <param name="required"></param>
/// <returns></returns>
public static IHtmlContent MyDecimalFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes, bool required = false, bool isPercent = false)//(this IHtmlHelper helper, string name, decimal? Value)
{
var modelExpression = GetModelExpression(helper, expression);
var str = @"
<div class='form-group col-md-6'>
<label class='formlabel' for='{0}'>{1}</label><input id='{0}' class='text-box' onkeyup=""this.value=this.value.replace(/[^0-9.-]/g,'')"" onblur=""this.value=(/^(-?0|-?[1-9]\d*)(\.\d*)?$/.test(this.value) ? this.value : '')"" data-val-required='请输入数值' type='text' value='{2}' name='{0}'{3} {6} />{4}
{5}
</div>";
//data-val='true' data-val-number='请输入数值'
var _required = modelExpression.Metadata.IsRequired || required;
var HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var sbAttribute = new StringBuilder();
object attrValue = null;
foreach (var a in HtmlAttributes)
{
sbAttribute.AppendFormat(" {0}=\"{1}\" ", a.Key, WebUtility.HtmlEncode(a.Value?.ToString()));
if (a.Key.ToLower() == "value")
{
attrValue = a.Value;
}
}
var setValueData = modelExpression.Model;
if (modelExpression.Model == null && attrValue != null)
{
setValueData = attrValue;
}
var afterAppend = "";
if (isPercent)
{
afterAppend = "%";
}
var m3 = helper.ValidationMessageFor(expression);
var displayName = helper.DisplayNameFor(expression);
var fullStr = string.Format(str, modelExpression.Name, displayName, setValueData
, _required ? string.Format(" data-val='true' data-val-required='{0} 字段是必需的'", displayName) : ""
, (_required ? " <span style='color:red'>*</span>" : "") + afterAppend, ToHtmlString(m3), sbAttribute, "{1,2}");
return new HtmlString(fullStr);
}
public static IHtmlContent MyIntFor<TModel, TValue>(this IHtmlHelper<TModel> helper,
Expression<Func<TModel, TValue>> expression, bool required = false)
{
var data = new { onkeyup = "this.value=this.value.replace(/[^0-9]/g,'')" };
return MyTextFor(helper, expression, data, required);
}
public static IHtmlContent MyTextFor<TModel, TValue>(this IHtmlHelper<TModel> helper,
Expression<Func<TModel, TValue>> expression, bool required = false, bool showLable = true)
{
return MyTextFor(helper, expression, null, required, showLable: showLable);
}
public static IHtmlContent MyTextFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
object htmlAttributes, bool required = false, string requireStr = "", bool showLable = true)
{
var modelExpression = GetModelExpression(helper, expression);
var str = showLable
? "<div class='form-group col-md-6'><label class='formlabel' for='{0}'>{1}</label><input id='{0}' class='text-box' type='text' value='{2}' name='{0}'{3} {6}/>{4}{5}</div>"
: "<div class='form-group col-md-6'><input id='{0}' class='text-box' type='text' value='{2}' name='{0}'{3} {6}/>{4}{5}</div>";
var HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var sbAttribute = new StringBuilder();
object attrValue = null;
foreach (var a in HtmlAttributes)
{
sbAttribute.AppendFormat(" {0}=\"{1}\" ", a.Key, WebUtility.HtmlEncode(a.Value?.ToString()));
if (a.Key.ToLower() == "value")
{
attrValue = a.Value;
}
}
var _required = modelExpression.Metadata.IsRequired || required;
var setValueData = modelExpression.Model;
var m3 = helper.ValidationMessageFor(expression);
if (modelExpression.Model == null && attrValue != null)
{
setValueData = attrValue;
}
var displayName = helper.DisplayNameFor(expression);
var fullStr = string.Format(str, modelExpression.Name, displayName, setValueData
, _required ? string.Format(" data-val='true' data-val-required='{0}{1}'", displayName, requireStr) : ""
, _required ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3), sbAttribute.ToString());
return new HtmlString(fullStr);
}
public static IHtmlContent MyTextAreaFor<TModel, TValue>(this IHtmlHelper<TModel> helper,
Expression<Func<TModel, TValue>> expression, int row)
{
return MyTextAreaFor(helper, expression, row, null);
}
public static IHtmlContent MyTextAreaFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, int row, object htmlAttributes)
{
var modelExpression = GetModelExpression(helper, expression);
var m3 = helper.ValidationMessageFor(expression);
//width:80%
var HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var sbAttribute = new StringBuilder();
foreach (var a in HtmlAttributes)
{
sbAttribute.AppendFormat(" {0}=\"{1}\" ", a.Key, WebUtility.HtmlEncode(a.Value?.ToString()));
}
var str = @"
<div class='form-group col-md-6'>
<label class='formlabel' for='{0}'>{1}</label>
<textarea id='{0}' class='text-box' {7} rows='{5}' name='{0}'{3} >{2}</textarea>{4} {6}
</div>";
var displayName = helper.DisplayNameFor(expression);
var fullStr = string.Format(str, modelExpression.Name,
displayName, modelExpression.Model,
modelExpression.Metadata.IsRequired ? string.Format(" data-val='true' data-val-required='{0} 字段是必需的'", displayName) : "",
modelExpression.Metadata.IsRequired ? " <span style='color:red'>*</span>" : "",
row,
ToHtmlString(m3),
sbAttribute);
return new HtmlString(fullStr);
}
public static IHtmlContent MyDateTimeFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool required = false)
{
var modelExpression = GetModelExpression(helper, expression);
var m3 = helper.ValidationMessageFor(expression);
var str = @"
<div class='form-group col-md-6'>
<div class='row'>
<label class='formlabel col-auto pl-0' for='{0}'>{1}</label>
<div class='col p-0'>
<input class='form_datetime text-box' size='16' id='{0}' type='text' value='{2}' name='{0}' {3} />
</div>
<div class='col-auto p-0'>
{4} {5}
</div>
</div>
</div>";
var valueStr = DateTime.Now.ToString();
if (modelExpression.Model != null)
{
DateTime.TryParse(modelExpression.Model + "", out var dtnew);
if (dtnew != DateTime.MinValue)
{
valueStr = dtnew.ToString("yyyy-MM-dd HH:mm");
}
}
var displayName = helper.DisplayNameFor(expression);
var _required = modelExpression.Metadata.IsRequired || required;
var fullStr = string.Format(str, modelExpression.Name, displayName, valueStr
, _required ? string.Format(" data-val='true' data-val-required='{0} 字段是必需的'", displayName) : ""
, _required ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3));
return new HtmlString(fullStr);
}
public static IHtmlContent MyDateFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool required = false)
{
var modelExpression = GetModelExpression(helper, expression);
var m3 = helper.ValidationMessageFor(expression);
var str = @"
<div class='form-group col-md-6'>
<label class='formlabel' for='{0}'>{1}</label><input id='{0}' class='text-box datepicker' type='text' value='{2}' name='{0}' {3} />{4}{5}
</div>";
var valueStr = "";
if (modelExpression.Model != null)
{
DateTime.TryParse(modelExpression.Model + "", out var dtnew);
if (dtnew != DateTime.MinValue)
{
valueStr = dtnew.ToString("yyyy-MM-dd");
}
}
var displayName = helper.DisplayNameFor(expression);
var _required = modelExpression.Metadata.IsRequired || required;
var fullStr = string.Format(str, modelExpression.Name, displayName, valueStr
, _required ? string.Format(" data-val='true' data-val-required='{0} 字段是必需的'", displayName) : ""
, _required ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3));
return new HtmlString(fullStr);
}
public static IHtmlContent MyDropdownFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IList<SelectListItem> list, string defaultValue = "", bool appendBlank = true, bool showLable = true)
{
return MyDropdownFor(helper: helper, expression: expression, list: list, htmlAttributes: null, defaultValue: defaultValue, appendBlank: appendBlank, showLable: showLable);
}
public static IHtmlContent MyDropdownFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IEnumerable<SelectItem> list, string defaultValue = "", bool appendBlank = true, bool showLable = true)
{
return MyDropdownFor(helper: helper, expression: expression, list: list, htmlAttributes: null, defaultValue: defaultValue, appendBlank: appendBlank, showLable: showLable);
}
public static IHtmlContent MyDropdownFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IEnumerable<SelectItem> list, object htmlAttributes, string defaultValue = "", bool appendBlank = true, bool showLable = true, bool showRequired = false, string userDefinedId = null)
{
return MyDropdownFor(helper: helper, expression: expression, list: list.AsSelectListItems(), htmlAttributes: htmlAttributes, defaultValue: defaultValue, appendBlank: appendBlank, showLable: showLable, showRequired: showRequired, userDefinedId: userDefinedId);
}
public static IHtmlContent MyDropdownFor<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IList<SelectListItem> list, object htmlAttributes, string defaultValue = "", bool appendBlank = true, bool showLable = true, bool showRequired = false, string userDefinedId = null)
{
if (appendBlank)
{
if (list.Count == 0 || list.Count > 0 && list[0].Value != "" && list[0].Text != "----")
{
list.Insert(0, new SelectListItem() { Value = "", Text = "----" });
}
}
var valueType = typeof(TValue);
var modelExpression = GetModelExpression(helper, expression);
var IsRequired = modelExpression.Metadata.IsRequired;
if (valueType.IsValueType && !valueType.GetCustomAttributes(typeof(RequiredAttribute), false).Any())
{
IsRequired = false;
}
SelectListItem defaultList = null;
if (!string.IsNullOrEmpty(defaultValue))
{
foreach (var selectListItem in list)
{
if (selectListItem.Value == defaultValue)
{
selectListItem.Selected = true;
defaultList = selectListItem;
}
}
}
else if (!string.IsNullOrEmpty(modelExpression.Model?.ToString()))
{
foreach (var selectListItem in list)
{
if (selectListItem.Value == modelExpression.Model?.ToString())
{
selectListItem.Selected = true;
}
}
}
if (defaultList != null)
{
list.Remove(defaultList);
list.Insert(0, defaultList);
}
var displayName = helper.DisplayNameFor(expression);
var m3 = helper.ValidationMessageFor(expression);
var fullName = userDefinedId.TrimToNull() ?? modelExpression.Name;
var str = showLable
? "<div class='form-group col-md-6'><label class='formlabel' for='{0}'>{1}</label>{2} {3} {4}</div>"
: "<div class='form-group col-md-6'><label class='formlabel' style='display:none' for='{0}'>{1}</label>{2} {3} {4}</div>";
var m2 = helper.DropDownList(fullName, list, null, htmlAttributes);
var fullStr = string.Format(str, fullName, displayName, ToHtmlString(m2)
, showRequired || IsRequired ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3));
var autoDropDownSet = string.Format(@" <script>jQuery(function() {{
try{{
$('#{0}').chosen({{search_contains: true}});
}}catch(e){{}}
}});</script>", fullName);
return new HtmlString(fullStr + autoDropDownSet);
}
public static IHtmlContent MyDropdownFor1<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IEnumerable<SelectItem> list, object htmlAttributes = null, string defaultValue = "", bool appendBlank = true, bool showLable = true)
{
return MyDropdownFor1(helper: helper, expression: expression, list: list.AsSelectListItems(),
htmlAttributes: htmlAttributes, defaultValue: defaultValue, appendBlank: appendBlank, showLable: showLable);
}
public static IHtmlContent MyDropdownFor1<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IEnumerable<string> list, object htmlAttributes = null, string defaultValue = "", bool appendBlank = true, bool showLable = true)
{
return MyDropdownFor1(helper: helper, expression: expression,
list: list.Select(n => new SelectListItem { Text = n, Value = n }).ToList(),
htmlAttributes: htmlAttributes, defaultValue: defaultValue, appendBlank: appendBlank, showLable: showLable);
}
public static IHtmlContent MyDropdownFor1<TModel, TValue>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
IList<SelectListItem> list, object htmlAttributes = null, string defaultValue = "", bool appendBlank = true, bool showLable = true)
{
if (appendBlank)
{
if (list.Count == 0 || list.Count > 0 && list[0].Value != "")
{
list.Insert(0, new SelectListItem() { Value = "", Text = "----" });
}
}
var modelExpression = GetModelExpression(helper, expression);
if (!string.IsNullOrEmpty(defaultValue))
{
foreach (var selectListItem in list)
{
if (selectListItem.Value == defaultValue)
{
selectListItem.Selected = true;
}
}
}
else if (!string.IsNullOrEmpty(modelExpression.Model?.ToString()))
{
foreach (var selectListItem in list)
{
if (selectListItem.Value == modelExpression.Model?.ToString())
{
selectListItem.Selected = true;
}
}
}
var displayName = helper.DisplayNameFor(expression);
var m3 = helper.ValidationMessageFor(expression);
var str = showLable
? "<div class='form-group col-md-6'><label class='formlabel' for='{0}'>{1}</label>{2} {3} {4}</div>"
: "<div class='form-group col-md-6'><label class='formlabel' style='display:none' for='{0}'>{1}</label>{2} {3} {4}</div>";
var m2 = helper.DropDownList(modelExpression.Name, list, null, htmlAttributes);
var fullStr = string.Format(str, modelExpression.Name, displayName, ToHtmlString(m2)
, modelExpression.Metadata.IsRequired ? " <span style='color:red'>*</span>" : "", ToHtmlString(m3));
return new HtmlString(fullStr);
}
public static IHtmlContent MyRadioButton(this IHtmlHelper helper, List<SelectListItem> list, string title, string controlName, string defaultValue, bool isRequired = false)
{
var str = @"<div class=""form-group col-md-6"" style=""height: auto;""><span>{2}</span>{0} {1}</div>";
//0 controlname,1 value ,2 checked,3 title,4 text
var singleRadio = @"<label><input type=""radio"" name=""{0}"" value=""{1}"" {2} data-val=""true"" id=""{0}""><span class="""">{3}</span></label>";
var checkstr = @" checked=""checked"" ";
var sb = new StringBuilder();
foreach (var val in list)
{
if (val.Value == defaultValue)
{
val.Selected = true;
sb.AppendFormat(singleRadio, controlName, val.Value, checkstr, val.Text);
}
else
{
sb.AppendFormat(singleRadio, controlName, val.Value, "", val.Text);
}
}
var required = isRequired ? @"<span style=""color:red"">*</span>" : "";
var fullStr = string.Format(str, sb, required, title);
return new HtmlString(fullStr);
}
}
public static class SearchExtensions
{
private static string ToHtmlString(IHtmlContent content)
{
using (var writer = new StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
public static IHtmlContent MyAceDropdownInput(this IHtmlHelper helper, string name, string label, IEnumerable<SelectItem> list)
{
return YcTemplateSearchExtensions.YcAceDropdownInput(helper, name, label, list.AsSelectListItems(), false);
}
public static IHtmlContent MyAceDropdownInput(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list)
{
return YcTemplateSearchExtensions.YcAceDropdownInput(helper, name, label, list, false);
}
public static IHtmlContent MyAceDropdownInput(this IHtmlHelper helper, string name, string label, IList<SelectItem> list, bool appendEmptyAll = true, bool enabled = true, object htmlAttributes = null, bool multiple = true)
{
return YcTemplateSearchExtensions.YcAceDropdownInput(helper, name, label, list.AsSelectListItems(), appendEmptyAll, enabled, htmlAttributes, multiple);
}
public static IHtmlContent MyAceDropdownInput(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list, bool appendEmptyAll = true, bool enabled = true, object htmlAttributes = null, bool multiple = true)
{
return YcTemplateSearchExtensions.YcAceDropdownInput(helper, name, label, list, appendEmptyAll, enabled, htmlAttributes, multiple);
}
public static IHtmlContent MyMultiSelectDropdown(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list)
{
return MyAceDropdownInputWithMultipleSearch(helper, name, label, list, false);
}
private static IHtmlContent MyAceDropdownInputWithMultipleSearch(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list, bool appendEmptyAll = true, bool enabled = true, object htmlAttributes = null, bool multiple = true)
{
var temp = "<span class=\"search-label\" for=\"{0}\">{1}</span>";
if (appendEmptyAll)
{
if (list != null && list.Count > 0 && list[0].Text != "全部")
{
list.Insert(0, new SelectListItem() { Text = "全部", Value = "" });
}
}
var option = multiple
? (object)(new { @class = "chosen-select", data_placeholder = "请选择 " + label, multiple = "" })
: (new { @class = "chosen-select", data_placeholder = "请选择 " + label });
var m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, option);
if (!enabled)
{
var inOption = multiple
? (new { @class = "chosen-select", @disabled = "disabled", data_placeholder = "请选择 " + label, multiple = "" })
: (object)(new { @class = "chosen-select", @disabled = "disabled", data_placeholder = "请选择 " + label });
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, inOption);
}
if (htmlAttributes != null)
{
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, htmlAttributes);
}
var m3 = new HtmlString(" <div class=\"search-group\">" + string.Format(temp, name, label) + ToHtmlString(m2) + "</div>");
return m3;
}
public static IHtmlContent MyAceDropdownInput2(this IHtmlHelper helper, string name, string label,
IEnumerable<string> list, bool appendEmptyAll = true, string defaultvalue = "", bool enabled = true, object htmlAttributes = null)
{
return MyAceDropdownInput2(helper: helper, name: name, label: label,
list: list.Select(n => new SelectListItem { Text = n, Value = n }).ToList(),
appendEmptyAll: appendEmptyAll, defaultvalue: defaultvalue, enabled: enabled, htmlAttributes: htmlAttributes);
}
public static IHtmlContent MyAceDropdownInput2(this IHtmlHelper helper, string name, string label,
IEnumerable<SelectItem> list, bool appendEmptyAll = true, string defaultvalue = "", bool enabled = true, object htmlAttributes = null)
{
return MyAceDropdownInput2(helper: helper, name: name, label: label,
list: list.Select(n => new SelectListItem { Text = n.Text, Value = n.Value }).ToList(),
appendEmptyAll: appendEmptyAll, defaultvalue: defaultvalue, enabled: enabled, htmlAttributes: htmlAttributes);
}
public static IHtmlContent MyAceDropdownInput2(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list, bool appendEmptyAll = true, string defaultvalue = "", bool enabled = true, object htmlAttributes = null)
{
var temp = "<span class=\"search-label\" for=\"{0}\">{1}</span>";
if (appendEmptyAll)
{
if (list != null && list.Count > 0 && list[0].Text != "全部")
{
list.Insert(0, new SelectListItem() { Text = "全部", Value = "" });
}
}
if (!string.IsNullOrEmpty(defaultvalue))
{
var dataSel = list.Where(l => l.Value == defaultvalue).FirstOrDefault();
if (dataSel != null)
{
dataSel.Selected = true;
}
}
var m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, htmlAttributes);
if (htmlAttributes == null)
{
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, new { @class = "", data_placeholder = "请选择 " + label });
}
if (!enabled)
{
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, new { @class = "", data_placeholder = "请选择 " + label, @disabled = "disabled" });
}
var m3 = new HtmlString(" <div class=\"search-group\">" + string.Format(temp, name, label) + ToHtmlString(m2) + "</div>");
return m3;
}
/*-----------------------------------------------------------------------------*/
public static IHtmlContent ShortInput(this IHtmlHelper helper, string name, string label)
{
var temp =
" <div class=\"search-group\"><span class=\"search-label\" for=\"{0}\">{1}</span><input class=\"search-input\" id=\"{0}\" name=\"{0}\" type=\"text\" value=\"{2}\" autocomplete=\"off\" /></div>";
return new HtmlString(string.Format(temp, name, label, helper.ViewData[name] ?? ""));
}
public static IHtmlContent SearchDate(this IHtmlHelper helper, string name, string label, object htmlAttributes = null)
{
var HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var sbAttribute = new StringBuilder();
foreach (var a in HtmlAttributes)
{
if (string.IsNullOrWhiteSpace((a.Value ?? "").ToString()))
{
sbAttribute.AppendFormat(" {0} ", a.Key);
}
else
{
sbAttribute.AppendFormat(" {0}={1} ", a.Key, a.Value);
}
}
var temp =
"<span class=\"search-label\" for=\"Date{0}\">{1}</span><input class=\"search-input datepicker\" id=\"Date{0}\" name=\"Date{0}\" type=\"text\" autocomplete=\"off\" {2} {3} />";
return new HtmlString(string.Format(temp, name, label
, (helper.ViewData["Date" + name] == null ? "" : string.Format("value='{0}'", helper.ViewData["Date" + name]))
, sbAttribute.ToString()));
}
public static IHtmlContent SearchDateRange(this IHtmlHelper helper, string name, string label, object htmlAttributes = null)
{
var HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var sbAttribute = new StringBuilder();
foreach (var a in HtmlAttributes)
{
if (string.IsNullOrWhiteSpace((a.Value ?? "").ToString()))
{
sbAttribute.AppendFormat(" {0} ", a.Key);
}
else
{
sbAttribute.AppendFormat(" {0}={1} ", a.Key, a.Value);
}
}
var temp =
" <div class=\"search-group\"><span class=\"search-label\" for=\"DateFrom{0}\">{1}</span><input {4} class=\"search-input datepicker\" id=\"DateFrom{0}\" name=\"DateFrom{0}\" type=\"text\" autocomplete=\"off\" {2} />-<input {4} class=\"search-input datepicker\" id=\"DateTo{0}\" name=\"DateTo{0}\" type=\"text\" autocomplete=\"off\" {3} /></div>";
return new HtmlString(string.Format(temp, name, label
, helper.ViewData["DateFrom" + name] == null ? "" : string.Format("value='{0}'", helper.ViewData["DateFrom" + name])
, helper.ViewData["DateTo" + name] == null ? "" : string.Format("value='{0}'", helper.ViewData["DateTo" + name])
, sbAttribute));
}
public static IHtmlContent SearchCheckbox(this IHtmlHelper helper, string name, string label, List<SelectListItem> list)
{
var temp = "<label><input type='checkbox' name='{0}' value='{1}' {3} id='{0}' /><span>{2}</span></label>";
var sb = new StringBuilder(string.Format("<span for='{0}' class='search-label'>{1}</span>", name, label));
string[] values = null;
if (helper.ViewData["Checkbox" + name] != null)
{
values = (helper.ViewData["Checkbox" + name] as string).Split(',');
}
foreach (var val in list)
{
var strChecked = "";
if (values != null)
{
foreach (var value in values)
{
if (value == val.Value)
{
strChecked = "checked='checked'";
}
}
}
sb.AppendFormat(temp, name, val.Value, val.Text, strChecked);
}
return new HtmlString(sb.ToString());
}
}
public static class YcTemplateSearchExtensions
{
private static string ToHtmlString(IHtmlContent content)
{
using (var writer = new StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
public static IHtmlContent YcAceDropdownInput(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list)
{
return YcAceDropdownInput(helper, name, label, list, false);
}
public static IHtmlContent YcAceDropdownInput(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list, bool appendEmptyAll = true, bool enabled = true, object htmlAttributes = null, bool multiple = true, bool searchBox = false, int dataWidth = 152)
{
var temp = "<span class=\"search-label\" for=\"{0}\">{1}</span>";
if (appendEmptyAll)
{
if (list != null && list.Count > 0 && list[0].Text != "全部")
{
list.Insert(0, new SelectListItem() { Text = "全部", Value = "" });
}
}
object option;
if (multiple)
{
option = new { @class = "selectpicker", multiple = "", data_live_search = "true", data_actions_box = "true", data_selected_text_format = "count > 1", data_width = $"{dataWidth}px" };
}
else
{
option = new { @class = "selectpicker", data_live_search = "true", data_actions_box = "true", data_width = $"{dataWidth}px" };
list.Insert(0, new SelectListItem() { Text = "---", Value = "" });
}
var m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, option);
if (!enabled)
{
var inOption = multiple
? (new { @class = "selectpicker", @disabled = "disabled", multiple = "", data_live_search = "true", data_actions_box = "true", data_selected_text_format = "count > 1", data_width = $"{dataWidth}px" })
: (object)(new { @class = "selectpicker", @disabled = "disabled", data_live_search = "true", data_actions_box = "true", data_selected_text_format = "count > 1", data_width = $"{dataWidth}px" });
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, inOption);
}
if (htmlAttributes != null)
{
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, htmlAttributes);
}
var m3 = new HtmlString(" <div class=\"search-group\">" + string.Format(temp, name, label) + ToHtmlString(m2) + "</div>");
return m3;
}
public static IHtmlContent YcShortInput(this IHtmlHelper helper, string name, string label)
{
var temp =
" <div class=\"from-group from-group-unit d-flex justify-content-end\"><span class=\"m-1\" for=\"{0}\">{1}</span><input class=\"form-control form-control-sm fixed-short-input\" id=\"{0}\" name=\"{0}\" value=\"{2}\" autocomplete=\"off\" /></div>";
return new HtmlString(string.Format(temp, name, label, helper.ViewData[name] ?? ""));
}
public static IHtmlContent YcAceDropdownInput2(this IHtmlHelper helper, string name, string label, IList<SelectListItem> list, bool appendEmptyAll = true, string defaultvalue = "", bool enabled = true, object htmlAttributes = null, int dataWidth = 152)
{
var temp = "<span class=\"m-1\" for=\"{0}\">{1}</span>";
if (appendEmptyAll)
{
if (list != null && list.Count > 0 && list[0].Text != "全部")
{
list.Insert(0, new SelectListItem() { Text = "全部", Value = "" });
}
}
if (!string.IsNullOrEmpty(defaultvalue))
{
var dataSel = list.Where(l => l.Value == defaultvalue).FirstOrDefault();
if (dataSel != null)
{
dataSel.Selected = true;
}
}
var m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, htmlAttributes);
if (htmlAttributes == null)
{
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, new { @class = "selectpicker form-control form-control-sm", data_width = $"{dataWidth}px" });
}
if (!enabled)
{
m2 = HtmlHelperSelectExtensions.DropDownList(helper, name, list, new { @class = "selectpicker form-control form-control-sm", data_width = $"{dataWidth}px", @disabled = "disabled" });
}
var m3 = new HtmlString(" <div class=\"from-group from-group-unit d-flex justify-content-end\">" + string.Format(temp, name, label) + ToHtmlString(m2) + "</div>");
return m3;
}
public static IHtmlContent YcSearchDateRange(this IHtmlHelper helper, string name, string label)
{
var temp =
" <div class=\"from-group form-group-unit d-flex justify-content-end\" data-dateFormat=\"yy/MM/dd\" style=\"width:230px\"><span class=\"m-1\" for=\"DateFrom{0}\">{1}</span><input class=\"form-control form-control-sm datepicker datepick-range-component\" id=\"DateFrom{0}\" name=\"DateFrom{0}\" autocomplete=\"off\" {2} />-<input class=\"form-control form-control-sm datepicker datepick-range-component\" id=\"DateTo{0}\" name=\"DateTo{0}\" autocomplete=\"off\" {3} /></div>";
return new HtmlString(string.Format(temp, name, label
, helper.ViewData["DateFrom" + name] == null ? "" : string.Format("value='{0}'", helper.ViewData["DateFrom" + name])
, helper.ViewData["DateTo" + name] == null ? "" : string.Format("value='{0}'", helper.ViewData["DateTo" + name])));
}
}
/// <summary>
///
/// </summary>
static class UnderlyingHelper
{
/// <summary>
/// 从标的代码中提取品种代码
/// <para>^[a-z|A-Z]+(?=\d+)</para>
/// </summary>
public static string GetVarietyCode(string underlyingCode)
{
if (string.IsNullOrWhiteSpace(underlyingCode)) { return ""; }
return Regex.Match(underlyingCode, @"^[a-z|A-Z]+(?=\d+)").Value;
}
}
public static class MyControls
{
public static IHtmlContent Btn(string text, string onClick, string icon = "", string id = "", string addclass = "")
{
var tagBuilder = new TagBuilder("button");
tagBuilder.Attributes["type"] = "button";
if (!string.IsNullOrWhiteSpace(id))
{
tagBuilder.Attributes["id"] = id.Trim();
}
tagBuilder.Attributes["class"] = "btn btn-primary " + addclass?.Trim();
tagBuilder.Attributes["onclick"] = onClick + ";return false;";
if (!string.IsNullOrEmpty(icon))
{
tagBuilder.InnerHtml.AppendFormat("<span class='glyphicon glyphicon-{0}'></span>", icon);
}
tagBuilder.InnerHtml.Append(text);
return tagBuilder;
}
public static IHtmlContent SearchBtn()
{
return new HtmlString("<button class=\"btn btn-primary\" onclick=\"return(SearchClick(true));\"><span class=\"glyphicon glyphicon-search\"></span> 查询</button>");
}
}
}