从下拉列表中删除项目 ASP.NET MVC 5 和 C#
Remove item from dropdownlist ASP.NET MVC 5 and C#
我的 ASP.NET MVC 5 项目中已经有了下拉列表。
我需要删除一个名为“Admin”的项目参数;我想在加载页面时将其从列表中删除。
这是我的 Razor 标记:
<div class="form-group">
@Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.DropDownListFor(model => model.RoleName, Model.VMRoles, new { @class = "form
control input-sm", multiple= "multiple" })
@Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger" })
</div>
</div>
这是 C# 控制器:
[HttpGet]
[Authorize]
public ActionResult Create()
{
var vm = new CreateUserViewModel
{
VMSisterConcerns = _sisterConcernService.GetAllSisterConcern().Select(c => new SelectListItem { Text = c.Name, Value = c.ConcernID.ToString() }).ToList(),
VMRoles = _roleService.GetAllRole().Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),
ConcernId = User.Identity.GetConcernId().ToString()
};
return View(vm);
}
这是模型:
public ICollection<System.Web.Mvc.SelectListItem> VMRoles { get; set; }
这是正确答案,感谢 @itsme86 他提到了如何理解 LINQ。
VMRoles = _roleService.GetAllRole().Where(r => r.name != "Admin").Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),
我的 ASP.NET MVC 5 项目中已经有了下拉列表。
我需要删除一个名为“Admin”的项目参数;我想在加载页面时将其从列表中删除。
这是我的 Razor 标记:
<div class="form-group">
@Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.DropDownListFor(model => model.RoleName, Model.VMRoles, new { @class = "form
control input-sm", multiple= "multiple" })
@Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger" })
</div>
</div>
这是 C# 控制器:
[HttpGet]
[Authorize]
public ActionResult Create()
{
var vm = new CreateUserViewModel
{
VMSisterConcerns = _sisterConcernService.GetAllSisterConcern().Select(c => new SelectListItem { Text = c.Name, Value = c.ConcernID.ToString() }).ToList(),
VMRoles = _roleService.GetAllRole().Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),
ConcernId = User.Identity.GetConcernId().ToString()
};
return View(vm);
}
这是模型:
public ICollection<System.Web.Mvc.SelectListItem> VMRoles { get; set; }
这是正确答案,感谢 @itsme86 他提到了如何理解 LINQ。
VMRoles = _roleService.GetAllRole().Where(r => r.name != "Admin").Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),