/ / Jak dodać dodatkowe htmlattributes w rozszerzeniu dla DropDownListFor - asp.net-mvc

Jak dodać dodatkowe htmlattributes w rozszerzeniu dla DropDownListFor - asp.net-mvc

Próbuję napisać rozszerzenie dla DropDownListFor:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
return htmlHelper.DropDownListFor(expression, selectList, null /* optionLabel */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}

To, co chcę osiągnąć, to to, czy włączona jest wartość false, ale jeśli jest włączona, to chcę ją dodać @disabled="disabled" do atrybutów html przed ich przekazaniem AnonymousObjectToHtmlAttributes.

Wszelkie pomysły, jak to zrobić?

Odpowiedzi:

30 dla odpowiedzi nr 1

Prosty! HtmlHelper.AnonymousObjectToHtmlAttributes zwraca RouteValueDictionary. Możesz dodać wartość do tego słownika, nie musisz dodawać właściwości do anonimowego obiektu.

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (!enabled)
{
attrs.Add("disabled", "disabled");
}
return htmlHelper.DropDownListFor(expression, selectList, null /* optionLabel */, attrs);
}

2 dla odpowiedzi nr 2

Rozwiązanie według dzieł archil. Jednak do tego, co próbujesz zrobić, to rozszerzenie jest przesadą.

Po prostu napisz w swoim widoku coś takiego:

@Html.DropDownListFor(m => m.Id, Model.Values, new { disabled = "disabled" })