I want to remove if-statements from my View, but I'm having problems with predefined controls like Html.DropDownList.
For example, I have an DropDownList that in some case contains empty selection (or in other words.. possibility to Not select something) and other case is that there is no empty selection.
<% if (Model.IsCreateEmptySelectionSet)
{ %>
<%= Html.DropDownList("InternalVariableTypeList", Model.InternalType, "-- select internal variable type --")%>
<% } %>
<% else
{ %>
<%= Html.Drop开发者_StackOverflow社区DownList("InternalVariableTypeList", Model.InternalType)%>
<% } %>
So, I would like create helper that would create correct DropDownList, but when I create my own helper I can't access Html.DropDownList. How is it used in correct way?
Html helpers could be used to clean the tag soup and also make your code more testable:
public static class HtmlExtensions
{
public static MvcHtmlString CustomDropDown<TModel>(this HtmlHelper<TModel> htmlHelper, IEnumerable<SelectListItem> selectList, bool isCreateEmptySelectionSet)
{
if (isCreateEmptySelectionSet)
{
return htmlHelper.DropDownList("InternalVariableTypeList", selectList, "-- select internal variable type --");
}
return htmlHelper.DropDownList("InternalVariableTypeList", selectList);
}
}
And use like this:
<%= Html.CustomDropDownList(
"InternalVariableTypeList",
Model.InternalType,
Model.IsCreateEmptySelectionSet)
%>
Remark: CustomDropDownList
is a very poorly chosen name, pick a more adapted one to your scenario.
精彩评论