Extending @Html.DropDownListFor

I would like to use the following code by extending the @Html.DropDownListFor helper. My controller gets a list, and I am adding a default value to the IEnumerable in my view model. However I don't want to write all of this every time I want a dropdown with a default value. So extending the helper seems logical.

public class SiteGetSitesViewModel
    public string SelectedSiteId { get; set; }
    public IEnumerable<SelectListItem> SiteListItems { get; set; }
public ActionResult GetSites()
    List<SiteDto> sites = _siteService.GetSites();
    const string defaultText = "Select a site";
    const string defaultValue = "-1";

    var siteGetSitesViewModel = new SiteGetSitesViewModel
            SiteListItems = Enumerable.Repeat(new SelectListItem
                    Selected = true,
                    Text = defaultText,
                    Value = defaultValue
                }, 1).Concat(sites.Select(s => new SelectListItem
                        Text = s.SiteName,
                        Value = s.SiteId.ToString()

    return PartialView("_GetSites", siteGetSitesViewModel);


Html.DropDownListFor supports adding a default value to the choices already, so there is no need to reinvent the wheel:

Use this overload:


    m => m.Property,
    "defaultOption", // the text for the default option goes here

Need Your Help

Size of jdom document vs single variables

java xml jsp session jdom

I planning on reading profile data from a xml file in JSP.

Open Tab Bar controller with all values on login

ios swift uitabbarcontroller presentviewcontroller

After successful login, i am trying to navigate to a tab bar controller. The code i have written is pasted below.