amh_300
amh_300

Reputation: 67

How can I add customized selection value into DropDownListFor with ViewBag for options?

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

Answers (1)

Yong Shun
Yong Shun

Reputation: 51420

  1. Create a variable (regionOptions) to hold the list of regions.

  2. 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));
  1. Remove the placeholder: "Select Region"
@Html.DropDownListFor(m => m.RegionID, (SelectList) ViewBag.RegionID, new {@class = "form-control", @data_val = "true", @data_val_required= "Region is required"})

Demo (MVC) @ .NET Fiddle

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

Related Questions