asp.net mvc - assign a dropdownListfor to an "All" option with value=0 -
i have dropdownlist in view want assign option value 0 suppose
<option value="0">all</option> <option value="1">account a</option> <option value="2">account b</option>
and on , if user dont select 1 option default selected value should 0 all.. have tried not working.
here code appreciated.
public class reportviewmodel { public selectlist account { get; set; } public string selectedaccount { get; set; } public selectlist user { get; set; } public string selecteduser { get; set; } public selectlist team { get; set; } public string selectedteam { get; set; } }
view
@html.dropdownlistfor(m => m.selectedaccount, (ienumerable<selectlistitem>)model.account, " ", new { @class = "form-control" }) @html.dropdownlistfor(m => m.selectedteam, (ienumerable<selectlistitem>)model.team, " ", new { @class = "form-control" })
controller
reportviewmodel.account = new selectlist(preflightdbcontext.accounts.where(o => o.accountid != 0 && o.deleted == false), "accountid", "accountname"); reportviewmodel.team = new selectlist(preflightdbcontext.teams.where(o => o.teamid != 0 && o.deleted == false), "teamid", "teamname");
you need construct list<selectlistitem>
in controller , add selectlistitem
text , value want. change property to
public ienumerable<selectlistitem> account { get; set; }
and in controller
list<selectlistitem> accounts = preflightdbcontext.accounts .where(o => o.accountid != 0 && o.deleted == false) .select(o => new selectlistitem() { value = accountid.tostring(), // assumes accountid not string text = accountname }).tolist(); accounts.insert(0, new selectlistitem() { value = "0", text = "all" }); reportviewmodel.account = accounts;
then in view
@html.dropdownlistfor(m => m.selectedaccount, model.account, new { @class = "form-control" })
(ditto team
)
Comments
Post a Comment