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

Answers


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
)

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.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.