views:

42

answers:

1

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.DropDownList("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?

+2  A: 

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.

Darin Dimitrov
Thanks, this was exactly what I needed! I didn't have "this HtmlHelper<TModel> htmlHelper" and therefore I didn't have access to the DropDownList
Tx3