Asp.net mvc MVC 4的DropDownList中的Optgroup不支持MVC验证 public static MvcHtmlString dropdownggrouplistfor(此HtmlHelper HtmlHelper、表达式表达式、IEnumerable
MVC 4的DropDownList中的Optgroup不支持MVC验证Asp.net mvc MVC 4的DropDownList中的Optgroup不支持MVC验证 public static MvcHtmlString dropdownggrouplistfor(此HtmlHelper HtmlHelper、表达式表达式、IEnumerable,asp.net-mvc,asp.net-mvc-4,Asp.net Mvc,Asp.net Mvc 4,MVC 4的DropDownList中的Optgroup不支持MVC验证 public static MvcHtmlString dropdownggrouplistfor(此HtmlHelper HtmlHelper、表达式表达式、IEnumerable selectList、字符串defaultText、对象htmlAttributes、bool已禁用) { 如果(已禁用) { IDictionary htmlAttributeMerge=新路由值字典(htmlAttributes); 添加
public static MvcHtmlString dropdownggrouplistfor(此HtmlHelper HtmlHelper、表达式表达式、IEnumerable selectList、字符串defaultText、对象htmlAttributes、bool已禁用)
{
如果(已禁用)
{
IDictionary htmlAttributeMerge=新路由值字典(htmlAttributes);
添加(“禁用”、“禁用”);
返回DropDownGroupListFor(htmlHelper、expression、selectList、defaultText、htmlAttributeMerge);
}
其他的
{
返回DropDownGroupListFor(htmlHelper、expression、selectList、defaultText、htmlAttributes);
}
}
//辅助方法
私有静态IEnumerable GetSelectData(此HtmlHelper HtmlHelper,字符串名称)
{
对象o=null;
如果(htmlHelper.ViewData!=null)
{
o=htmlHelper.ViewData.Eval(名称);
}
如果(o==null)
{
抛出新的InvalidOperationException(
字符串格式(
CultureInfo.CurrentCulture,
“缺少选择数据”,
名称
“IEnumerable”);
}
IEnumerable selectList=o作为IEnumerable;
如果(selectList==null)
{
抛出新的InvalidOperationException(
字符串格式(
CultureInfo.CurrentCulture,
“选择数据类型错误”,
名称
o、 GetType().FullName,
“IEnumerable”);
}
返回选择列表;
}
内部静态字符串ListItemToOption(GroupedSelectListItem)
{
标记生成器=新标记生成器(“选项”)
{
InnerHtml=HttpUtility.HtmlEncode(item.Text)
};
如果(item.Value!=null)
{
builder.Attributes[“value”]=item.value;
}
如果(选定项)
{
builder.Attributes[“selected”]=“selected”;
}
返回builder.ToString(TagRenderMode.Normal);
}
私有静态MvcHtmlString SelectInternal(此HtmlHelper HtmlHelper、字符串选项标签、字符串名称、IEnumerable selectList、bool allowMultiple、IDictionary HTMLAttribute)
{
name=htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(名称);
if(String.IsNullOrEmpty(name))
{
抛出新ArgumentException(“Null或空”、“name”);
}
bool usedViewData=false;
//如果我们得到一个空的selectList,请尝试使用ViewData来获取项目列表。
如果(selectList==null)
{
selectList=GetSelectData(htmlHelper,名称);
usedViewData=true;
}
对象defaultValue=(allowMultiple)?htmlHelper.GetModelStateValue(名称,类型(字符串[])):htmlHelper.GetModelStateValue(名称,类型(字符串));
//如果我们还没有使用ViewData来获取整个项目列表,那么我们需要
//在使用参数提供的值之前,请先使用ViewData提供的值。
如果(!usedViewData)
{
if(defaultValue==null)
{
defaultValue=htmlHelper.ViewData.Eval(名称);
}
}
如果(默认值!=null)
{
IEnumerable defaultValues=(allowMultiple)?作为IEnumerable的defaultValue:new[]{defaultValue};
IEnumerable values=从defaultValues中的对象值选择Convert.ToString(值,CultureInfo.CurrentCulture);
HashSet selectedValues=新的HashSet(值,StringComparer.OrdinalIgnoreCase);
List newSelectList=新列表();
foreach(选择列表中的GroupedSelectListItem项)
{
item.Selected=(item.Value!=null)?selectedValues.Contains(item.Value):selectedValues.Contains(item.Text);
新闻选择列表。添加(项);
}
selectList=新闻选择列表;
}
//将每个ListItem转换为标记
StringBuilder listItemBuilder=新建StringBuilder();
//使optionLabel成为第一个渲染的项。
if(optionLabel!=null)
{
AppendLine(ListItemToOption(新的GroupedSelectListItem(){Text=optionLabel,Value=String.Empty,Selected=false}));
}
foreach(selectList.GroupBy中的var组(i=>i.GroupKey))
{
string groupName=selectList.Where(i=>i.GroupKey==group.Key).Select(it=>it.groupName.FirstOrDefault();
AppendLine(string.Format(“,groupName,group.Key));
foreach(组中的GroupedSelectListItem项目)
{
AppendLine(ListItemToOption(item));
}
listItemBuilder.AppendLine(“”);
}
标记生成器标记生成器=新标记生成器(“选择”)
{
InnerHtml=listItemBuilder.ToString()
};
foreach(htmlAttributes中的var htmlAttribute)
{
tagBuilder.MergeAttribute(
htmlAttribute.Key.Replace(“”,“-”),
(字符串)htmlAttribute.Value
);
}
tagBuilder.MergeAttributes(HtmlatAttributes);
tagBuilder.MergeAttribute(“name”,name,true/*replaceExisting*/);
tagBuilder.GenerateId(名称);
如果(允许多个)
{
tagBuilder.MergeAttribute(“多个”、“多个”);
}
//如果命名字段有任何错误,我们将添加css属性。
模型状态模型状态;
if(htmlHelper.ViewData.ModelState.TryGetValue(名称,out ModelState))
{
如果(modelState.Errors.Count>0)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
}
返回MvcHtmlString.Create(tagBuilder.ToString());
}
内部静态对象GetModelStateValue(此
public static MvcHtmlString DropDownGroupListFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, IEnumerable<GroupedSelectListItem> selectList, string defaultText, object htmlAttributes, bool isDisabled)
{
if (isDisabled)
{
IDictionary<string, object> htmlAttributeMerge = new RouteValueDictionary(htmlAttributes);
htmlAttributeMerge.Add("disabled", "disabled");
return DropDownGroupListFor(htmlHelper,expression, selectList, defaultText, htmlAttributeMerge);
}
else
{
return DropDownGroupListFor(htmlHelper, expression, selectList, defaultText, htmlAttributes);
}
}
// Helper methods
private static IEnumerable<GroupedSelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
object o = null;
if (htmlHelper.ViewData != null)
{
o = htmlHelper.ViewData.Eval(name);
}
if (o == null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"Missing Select Data",
name,
"IEnumerable<GroupedSelectListItem>"));
}
IEnumerable<GroupedSelectListItem> selectList = o as IEnumerable<GroupedSelectListItem>;
if (selectList == null)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"Wrong Select DataType",
name,
o.GetType().FullName,
"IEnumerable<GroupedSelectListItem>"));
}
return selectList;
}
internal static string ListItemToOption(GroupedSelectListItem 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);
}
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<GroupedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
{
name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (String.IsNullOrEmpty(name))
{
throw new ArgumentException("Null Or Empty", "name");
}
bool usedViewData = false;
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = GetSelectData(htmlHelper, name);
usedViewData = true;
}
object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(name, typeof(string[])) : htmlHelper.GetModelStateValue(name, typeof(string));
// If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (!usedViewData)
{
if (defaultValue == null)
{
defaultValue = htmlHelper.ViewData.Eval(name);
}
}
if (defaultValue != null)
{
IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };
IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
List<GroupedSelectListItem> newSelectList = new List<GroupedSelectListItem>();
foreach (GroupedSelectListItem item in selectList)
{
item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
newSelectList.Add(item);
}
selectList = newSelectList;
}
// Convert each ListItem to an <option> tag
StringBuilder listItemBuilder = new StringBuilder();
// Make optionLabel the first item that gets rendered.
if (optionLabel != null)
{
listItemBuilder.AppendLine(ListItemToOption(new GroupedSelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }));
}
foreach (var group in selectList.GroupBy(i => i.GroupKey))
{
string groupName = selectList.Where(i => i.GroupKey == group.Key).Select(it => it.GroupName).FirstOrDefault();
listItemBuilder.AppendLine(string.Format("<optgroup label=\"{0}\" value=\"{1}\">", groupName, group.Key));
foreach (GroupedSelectListItem item in group)
{
listItemBuilder.AppendLine(ListItemToOption(item));
}
listItemBuilder.AppendLine("</optgroup>");
}
TagBuilder tagBuilder = new TagBuilder("select")
{
InnerHtml = listItemBuilder.ToString()
};
foreach (var htmlAttribute in htmlAttributes)
{
tagBuilder.MergeAttribute(
htmlAttribute.Key.Replace('_', '-'),
(string)htmlAttribute.Value
);
}
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("name", name, true /* replaceExisting */);
tagBuilder.GenerateId(name);
if (allowMultiple)
{
tagBuilder.MergeAttribute("multiple", "multiple");
}
// If there are any errors for a named field, we add the css attribute.
ModelState modelState;
if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState))
{
if (modelState.Errors.Count > 0)
{
tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
}
return MvcHtmlString.Create(tagBuilder.ToString());
}
internal static object GetModelStateValue(this HtmlHelper helper, string key, Type destinationType)
{
ModelState modelState;
if (helper.ViewData.ModelState.TryGetValue(key, out modelState))
{
if (modelState.Value != null)
{
return modelState.Value.ConvertTo(destinationType, null /* culture */);
}
}
return null;
}