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..
You can add a
null
option to the dropdownlist by using one of the overloads ofDropDownlistFor()
that accepts aoptionLabel
, for examplewhich 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 ownIEnumerable<SelectListItem>
in the controller and pass it to the view. I would recommend using view model with aIEnumerable<SelectListItem>
property for the options, but usingViewBag
, the code in the controller would beNote that I have given the
ALL
option a value of-1
assuming that none of yourEmpId
values will be-1
Then in the view, your code to generate the dropdownlist will be
Not sure why your wanting to change the
id
attribute fromid="EmpId"
toid="ddlEmp"
?Then in the POST method, first check if
ModelState
is invalid (if the user selected the"--select--"
option, a value ofnull
will be posted and the model will be invalid), so return the view (don't forget to reassign theViewBag.test
property).If
ModelState
is valid, then check the value ofmodel.EmpId
. If its-1
, then the user selected"ALL"
, otherwise they selected a specific option.