asp.net - Extending @Html.DropDownListFor -
i use following code extending @html.dropdownlistfor
helper. controller gets list, , adding default value ienumerable
in view model. don't want write of every time want dropdown default value. extending 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 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 default value choices already, there no need reinvent wheel:
use overload:
http://msdn.microsoft.com/en-us/library/ee703567(v=vs.108).aspx
@html.dropdownlistfor( m => m.property, getselectlist(), "defaultoption", // text default option goes here null )
Comments
Post a Comment