Set dropdownListfor to "All" option with value = 0
I have a dropdownList for my view to which I want to assign an All option with a value of 0 Suppose
<option value="0">All</option>
<option value="1">Account A</option>
<option value="2">Account B</option>
And so on, if the user doesn't select any default option, their selected value should be 0. Everything .. what I've tried doesn't work.
here is my code, any help would be 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, " ALL ", new { @class = "form-control" })
@Html.DropDownListFor(m => m.SelectedTeam, (IEnumerable<SelectListItem>)Model.Team, " ALL ", 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");
+3
source to share
1 answer
You need to build List<SelectListItem>
in your controller and add SelectListItem
with the text and value you want. Change your ownership to
public IEnumerable<SelectListItem> Account { get; set; }
and in the controller
List<SelectListItem> accounts = preFlightDbContext.Accounts
.Where(o => o.AccountId != 0 && o.Deleted == false)
.Select(o => new SelectListItem()
{
Value = AccountId.ToString(), // assumes AccountId is not a string
Text = AccountName
}).ToList();
accounts.Insert(0, new SelectListItem() { Value = "0", Text = "All" });
reportViewModel.Account = accounts;
then in the view
@Html.DropDownListFor(m => m.SelectedAccount, Model.Account, new { @class = "form-control" })
(same for Team
)
+4
source to share