//把数字转成枚举
public static T[] NumStringsToEnums<T>(string enumNumString ) //where T:Enum
{
if (string.IsNullOrEmpty(enumNumString)) return null;
string[] aryNums = enumNumString.Split(','); Type enumType = typeof(T); List<T> list = new List<T>();
for(int i=0;i< aryNums.Length; i++)
{
int num = 0;
int.TryParse(aryNums[i].Trim(), out num);
if (num == 0) continue; Array enumValues = Enum.GetValues(enumType);
foreach (Enum enumValue in enumValues)
{
Int32 key = Convert.ToInt32(enumValue);
if (key == num)
{
list.Add((T)(object)enumValue);
break;
}
}
}
return list.ToArray();
}
//判断字符串数字是否是枚举中的值
public static bool HasEnumInNumString<T>(string enumNumString, T findValue) //where T:Enum
{
T[] enums = NumStringsToEnums<T>(enumNumString);
if (enums == null) return false; for(int i=0; i<enums.Length; i++)
{
if((int)(object)enums[i]== (int)(object)findValue)
{
return true;
}
}
return false;
} //数字的枚举串变成汉字
public static string[] EnumNumsToStrings<T>(string enumNumString)
{
if (string.IsNullOrEmpty(enumNumString)) return new string[0]; T[] enums = NumStringsToEnums<T>(enumNumString);
string[] chinese = new string[enums.Length];
for(int i=0; i<enums.Length; i++)
{
chinese[i] = GetEnumCustomDescription(enums[i]);
}
return chinese;
} //数字的枚举串变成前端复选框(包括没有选中的)
public static Tuple<T, string, bool> [] EnumNumsToCheckBoxInfo<T>(string enumNumString)
{
Type enumType = typeof(T);
Array enumValues = Enum.GetValues(enumType);
int n = enumValues.Length;
Tuple<T, string, bool>[] tuples = new Tuple<T, string, bool>[n];
for (int i = 0; i < n; i++)
{
T enumValue = (T)(object)enumValues.GetValue(i);
string chinese = GetEnumCustomDescription((Enum)(object)enumValue);//GetDescription((Enum)(object)enumValue,true);
bool found = HasEnumInNumString(enumNumString, enumValue); tuples[i] = new Tuple<T, string, bool>(enumValue,chinese, found);
}
return tuples;
}
//枚举值转换成前端需要的复选框需要的HTML
public static string EnumNumsToCheckBoxHtml<T>(string enumNumString, string inputVarName,string seperator)
{
StringBuilder sb = new StringBuilder();
Tuple<T, string, bool>[] tuples = EnumNumsToCheckBoxInfo<T>(enumNumString);
for (int i = 0; i < tuples.Length; i++)
{
sb.Append("<input type=\"checkbox\" value=\"" + (int)(object)tuples[i].Item1 + "\""
+ (tuples[i].Item3 ? " checked " : "")
+ " name=\"" + inputVarName + "\">" + tuples[i].Item2+ seperator );
//< input type = "checkbox" value = "100" name = "checkboxValue" checked > gif上传阿里云 & nbsp;
}
return sb.ToString();
}
调用:
ViewData["bookAttributeHtml"] =
EnumUtil.EnumNumsToCheckBoxHtml<枚举类>("", "前端checkName", "分隔符");
前端:
<div class="form-group group-user-group">
<label class="col-sm-2 col-xs-2 control-label">书属性:</label>
<div class="col-sm-10 col-xs-10">
@Html.Raw(ViewData["bookAttributeHtml"])
</div>
</div>
显示: