Reputation: 67
I have a DropDownListFor with ViewBag as SelectList and looking to add one more option into dropdown with text as "Not Applicable" and value null.
Code on the ViewData:
ViewData["RegionID"] = new SelectList(_context.Region, nameof(LocationMaster.Region.RegionId), nameof(LocationMaster.Region.Name));
Current code on DropDownListFor
@Html.DropDownListFor(m => m.RegionID, (SelectList) ViewBag.RegionID, "Select Region", new {@class = "form-control", @data_val = "true", @data_val_required= "Region is required"})
Can I like append or insert one more item into the ViewData?
Upvotes: 0
Views: 36
Reputation: 51420
Create a variable (regionOptions
) to hold the list of regions.
With Insert(int index, T value)
to add a default option as the first element of the regionOptions
array.
var regionOptions = _context.Region.Select(x => new
{
RegionId = (int?)x.RegionId,
Name = x.Name
}).ToList();
regionOptions.Insert(0, new { RegionId = (int?)null, Name = "Not Applicable" });
ViewData["RegionID"] = new SelectList(regionOptions, nameof(LocationMaster.Region.RegionId), nameof(LocationMaster.Region.Name));
@Html.DropDownListFor(m => m.RegionID, (SelectList) ViewBag.RegionID, new {@class = "form-control", @data_val = "true", @data_val_required= "Region is required"})
Note that you should remove the data validation @data_val = "true", @data_val_required= "Region is required"
if you allow the RegionID
drop-down list as not mandatory.
Or as you add the placeholder: "Select Region", you don't have to manually add the default option into ViewData["RegionID"]
. By default its value is blank.
Upvotes: 0