-->

Include 'ALL' option in dropdownlist bind

2019-09-09 11:39发布

问题:

I have bind the dropdownlist in view by Viewbag from controller as following :

ViewBag.test = from p in _userRegisterViewModel.GetEmpPrimary().ToList().Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
                           select new
                           {
                Id = p.EmpId,
                Name =  p.First_Name.Trim() + " " + p.Last_Name.Trim()
            };

In view I have bind as following :

@Html.DropDownListFor(model => model.EmpId, new SelectList(@ViewBag.test, "Id", "Name"),
                        new { @class = "form-control", id="ddlEmp" })

Now i want to Insert "ALL" and "--Select--" in this dropdownlist.. How can i do this.. Can anyone help me to do this.. Thanks in advance..

回答1:

You can add a null option to the dropdownlist by using one of the overloads of DropDownlistFor() that accepts a optionLabel, for example

@Html.DropDownListFor(m => m.EmpId, new SelectList(@ViewBag.test, "Id", "Name"), "--select--", new { @class = "form-control", id="ddlEmp" })

which will generate the first option as <option value="">--select--</option>

However, if you want to include options with both "--select--" and "ALL" you will need to generate you own IEnumerable<SelectListItem> in the controller and pass it to the view. I would recommend using view model with a IEnumerable<SelectListItem> property for the options, but using ViewBag, the code in the controller would be

List<SelectListItem> options = _userRegisterViewModel.GetEmpPrimary()
    .Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
    .Select(a => new SelectListItem
    {
        Value = a.EmpId.ToString(),
        Text = a.First_Name.Trim() + " " + a.Last_Name.Trim()
    }).ToList();
// add the 'ALL' option
options.Add(new SelectListItem(){ Value = "-1", Text = "ALL" });
ViewBag.test = options;

Note that I have given the ALL option a value of -1 assuming that none of your EmpId values will be -1

Then in the view, your code to generate the dropdownlist will be

 @Html.DropDownListFor(m => m.EmpId, (Ienumerable<SelectListItem>)ViewBag.test, "--select--", new { @class = "form-control" })

Not sure why your wanting to change the id attribute from id="EmpId" to id="ddlEmp"?

Then in the POST method, first check if ModelState is invalid (if the user selected the "--select--" option, a value of null will be posted and the model will be invalid), so return the view (don't forget to reassign the ViewBag.test property).

If ModelState is valid, then check the value of model.EmpId. If its -1, then the user selected "ALL", otherwise they selected a specific option.