我正在使用此代码生成自定义DropDownListFor
public static MvcHtmlString LookupFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string lookup = metadata.PropertyName;
IEnumerable<lookup> list = Get(lookup);
IEnumerable<SelectListItem> items = list.Select(o => new SelectListItem
{
Text = o.title,
Value = o.id.ToString(),
Selected = o.id.Equals(metadata.Model)
}).ToList();
string id = "_" + (new Random()).Next(10000);
MvcHtmlString dropDown = htmlHelper.DropDownListFor(expression, items, "---", new {title = lookup, id});
return dropDown;
}
是否可以将HTML attribute
添加到某些 options
?
答案 0 :(得分:2)
您需要在class
前加@
,因为class是C#中的关键字:
MvcHtmlString dropDown = htmlHelper.DropDownListFor(expression, items, "---", new { @class = "cssClass", title = lookup, id});
答案 1 :(得分:0)
我为此目的找到了解决方案
public static HtmlString LookupFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string lookup = metadata.PropertyName;
IEnumerable<lookup> list = Get(lookup).ToList();
IEnumerable<SelectListItem> items = list.Select(o => new SelectListItem
{
Text = o.title,
Value = o.id.ToString(),
Selected = o.id.Equals(metadata.Model)
}).ToList();
string id = "_" + (new Random()).Next(10000);
MvcHtmlString dropDown = htmlHelper.DropDownListFor(expression, items, "---", new { title = lookup, id });
var xml = XDocument.Parse(dropDown.ToHtmlString());
var xml_select = xml.Element("select");
if (xml_select != null)
{
var options = xml_select.Elements("option");
foreach(var c in options )
{
var val_attribute = c.Attribute("value");
if (val_attribute != null)
{
string value = val_attribute.Value;
int tmp;
if (Int32.TryParse(value,out tmp))
{
var fd = list.FirstOrDefault(o => o.id == Convert.ToInt32(value));
if (fd == null) continue;
if (!fd.active)
{
c.SetAttributeValue("class", "deactive-lookup");
}
}
}
}
}
string html_string;
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xml.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
html_string = stringWriter.GetStringBuilder().ToString();
}
}
return new HtmlString(html_string);
}