0

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.

2 Answers 2

1

To add a default item you can try

model.Items.Insert(0, new SelectListItem { Text = "Please Select", Value = "-1" });

That will push the item to the top of the select list for you. Do this after you have called

model.Items = _context.SomeTable.Select(m => new SelectListItem()
{
    Text = m.SomeName,
    Value = m.SomeId
}).ToList();

It's important that you add a call to ToList() though, so that you are working with a projected list of items, not just the enumerator.

Sign up to request clarification or add additional context in comments.

4 Comments

Even after appending .ToList() I don't have an option of .Insert(...)
Ahh, OK. What type is Items?
It's an IEnumerable<SelectListItem>
Change it to be IList<SelectListItem>. That way, Insert will be available to you.
1

There is an override for 'DropDownListFor' that takes an 'optionLabel' as an argument

@Html.DropdownListFor(m => m.id, "select one", Model.selectList, new {})

You might want to check what value that it generates for that option. I think its either 0 or -1

2 Comments

Thank you Shoe. I was hoping to do this in the Controller and Jason's answer helped me out.
The option label argument achieves the same affect just that you know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.