My Model contains an IEnumerable<SelectListItem> and the View contains a DropDownListFor that works fine with the exception that I need to include a default "Select an Option" with a value of -1 in some cases.
In the Controller:
model.Items = _context.SomeTable.Select(m => new SelectListItem()
{
Text = m.SomeName,
Value = m.SomeId
});
In the View:
@Html.DropDownListFor(
w => Model.ItemId,
new SelectList(Model.Items, "Value", "Text", Model.ItemId),
new { @class = "form-control text-left" })
Between the Controller or View, how can I add the following as the first option and conditionally selected (if ItemId == -1)?
<option value="Select an Item">Select an Item</option>
Since the logic that determines whether there is an option currently selected is in the Controller I would prefer to add this in the Controller - if possible. Or, if i can get the <option ... added in the View and be selected when the Controller passes -1 as ItemId that would work too.