Search code examples
c#asp.netasp.net-mvc-5

Remove item from dropdownlist ASP.NET MVC 5 and C#


I do already have dropdownlist in my ASP.NET MVC 5 project.

I need to remove one of the item parameter call it "Admin"; I want remove it from the list when the page is loaded.

This is my Razor markup:

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

And this the C# controller:

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

And this the model:

public ICollection<System.Web.Mvc.SelectListItem> VMRoles { get; set; }

Solution

  • Here is the correct answer thanks for @itsme86 he mention How to understand LINQ .

    VMRoles = _roleService.GetAllRole().Where(r => r.name != "Admin").Select(r => new SelectListItem { Text = r.Name, Value = r.Name }).ToList(),