JohnMighty
JohnMighty

Reputation: 73

How to extend the DropDownListFor() in MVC

I'm trying to extend DropDownListFor in such a way that to preserve the original functionality, but add the functionality that if the selected value that is given is Null, to a new value to the SelectListItem list such as 'Select an item'.

How would you do that?

EDIT: (I wasn't clear at the beginning)

If we look at the default DropDownListFor behavior, the extension gets a list of SelectItems and the 'selected' value. In my app, sometimes the 'selected' value is Null, thus no option is selected from the SelectItems list. I would like to change the default behavior in such a way, that if my 'selected' value is Null, then the DropDown will add automatically a new value such as 'Select an Item' and select it as the 'selected'.

Hope it's better now :)

Thanks

Upvotes: 1

Views: 4954

Answers (1)

JohnMighty
JohnMighty

Reputation: 73

OK, Did it! For future reference here is the solution:

I've create an extension method for the DropDownListFor:

public static MvcHtmlString KeywordDropDownListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression,
                                                   IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
    Func<TModel, TValue> method = expression.Compile();
    string value = method(helper.ViewData.Model) as string;

    if (String.IsNullOrEmpty(value))
    {
        List<SelectListItem> newItems = new List<SelectListItem>();
        newItems.Add(new SelectListItem
        {
            Selected = true,
            Text = Strings.ChooseAKeyword,
            Value = String.Empty
        });
        foreach (SelectListItem item in selectList)
        {
            newItems.Add(item);
        }

        return helper.DropDownListFor(expression, newItems, htmlAttributes);
    }

    return helper.DropDownListFor(expression, selectList, htmlAttributes);
}

Upvotes: 2

Related Questions