user1935467
user1935467

Reputation: 13

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);
}

Upvotes: 1

Views: 318

Answers (1)

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

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

Use this overload:

http://msdn.microsoft.com/en-us/library/ee703567(v=vs.108).aspx

@Html.DropDownListFor(
    m => m.Property,
    GetSelectList(),
    "defaultOption", // the text for the default option goes here
    null
)

Upvotes: 2

Related Questions