我有一个类似的要求,我创建了一个扩展。希望它对想要创建扩展的人有所帮助。
public class vmListItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Tag { get; set; }
}
public class vmAttribute
{
public string Key { get; set; }
public string Value { get; set; }
}
public static MvcHtmlString DropDownListForWithTag(this HtmlHelper helper, string id, List<vmAttribute> attributes, List<vmListItem> items, int idSelected, string tagName = "tag", string textHeader= "")
{
var select = new TagBuilder("select");
select.GenerateId(id);
select.MergeAttribute("name", id);
foreach (vmAttribute att in atributos) select.MergeAttribute(att.Key, att.Value);
TagBuilder headerOption = new TagBuilder("option");
headerOption .MergeAttribute("value", null);
headerOption .InnerHtml = textHeader;
select.InnerHtml += headerOption ;
foreach(var item in items)
{
TagBuilder option = new TagBuilder("option");
option.MergeAttribute("value", item.Id.ToString());
option.MergeAttribute("data-" + tagName, item.Tag);
if (idSelected == item.Id) option.MergeAttribute("selected", "selected");
option.InnerHtml = item.Name;
select.InnerHtml += option.ToString();
}
return new MvcHtmlString(select.ToString());
}
@Html.DropDownListForWithTag("MovimientoBienMotivoId", new List<vmAttribute> {
new vmAttribute("class", "form-control"),
new vmAttribute("data-val", "true"),
new vmAttribute("data-val-required", "El campo Motivo es obligatorio"),
new vmAttribute("onchange", "movValidarCambioMotivo()"),
}, (List<vmListItem>)ViewBag.MovimientoBienMotivoId, Model.MovimientoBienMotivoId, "codigo", "Seleccione")
@Html.ValidationMessageFor(model => model.ColumnId, "", new { @class = "text-danger" })