asp.net-mvc - 将 dropdownListfor 分配给 value=0 的 "All"选项

标签 asp.net-mvc html.dropdownlistfor

我的 View 中有一个 dropdownList,我想为其分配值为 0 的 All 选项假设

<option value="0">All</option>
<option value="1">Account A</option>
<option value="2">Account B</option>

依此类推,如果用户默认情况下不选择任何一个选项,则其选择的值应为 0 All..我尝试过的方法不起作用。

这是我的代码,任何帮助将不胜感激。

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

查看

@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");

最佳答案

您需要构建List<SelectListItem>在 Controller 中添加 SelectListItem与您想要的文本和值。将您的属性更改为

public IEnumerable<SelectListItem> Account { get; set; }

在 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;

然后在 View 中

@Html.DropDownListFor(m => m.SelectedAccount, Model.Account, new { @class = "form-control" })

(Team 同上)

关于asp.net-mvc - 将 dropdownListfor 分配给 value=0 的 "All"选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30640740/

相关文章:

php - CakePHP 和 codeigniter 框架与 ASP.NET MVC 框架相比如何?

c# - MVC5 中数据库的下拉列表

asp.net-mvc - 页面刷新后下拉列表值返回---select---

asp.net-mvc - 在 asp.net-mvc 站点上,为什么 html DropdownlistFor() 不能正常工作?

asp.net-mvc - MVC 下拉列表 : Setting the value and text based upon table in database

c# - 如何在我的 C# Controller 中获取 Ajax post 数组?

asp.net-mvc - Application Insights 未显示服务器响应时间、服务器请求或失败请求的数据

javascript - 如何更改Kendo TimePicker的禁用属性?

asp.net-mvc - $.ajax( { 异步 : false } ) request is still firing asynchronously?