1

I tried this accepted answer, but it seems like this may be handled differently in the latest version of ASP.NET Core. I got no selected attribute at all from this:

<select class="form-control" asp-for="Status">
    <option></option>
    @foreach (var option in Enum.GetNames(typeof(StatusOptions))) {
        <option value="@option" @{if (option == Model.Status) { <text>selected="true"</text> } }>@option</option>
    }
</select>

As an alternative, I tried this and got selected="selected", but Visual Studio gives me a warning that @selected is not a valid value of attribute of 'selected'.

<select class="form-control" asp-for="Status">
    <option></option>
    @foreach (var option in Enum.GetNames(typeof(StatusOptions))) {
        bool selected = option == Model.Status;
        <option value="@option" selected="@selected">@option</option>
    }
</select>

I can use that, but I have to ignore the warning and it doesn't render exactly what I want. Is there a way to get:

<option value="firstOption" selected>firstOption</option>
Community
  • 1
  • 1
Shaun
  • 2,012
  • 20
  • 44
  • You do not set the `selected` property. The Tag Helper does that based on the value of the property you binding to. - `` –  Dec 20 '16 at 21:16

2 Answers2

1

I think that I would not enumerate the StatusOptions here. I would probably put this as a property on my Model.

public List<SelectListItem> StatusOptions => Enum.GetNames(typeof(StatusOptions)).Select(o => new SelectListItem {
   Text = o,
   Value = o,
   Selected = o == this.Status
}).ToList();

Then in the razor view:

@Html.DropDownListFor(m => m.Status, Model.StatusOptions, new { @class="form-control", asp_for = "status" })

This should do what you want.

bluetoft
  • 5,373
  • 2
  • 23
  • 26
  • Is there a way to add an empty first option to that helper or does it need to be injected into the `StatusOptions` list? – Shaun Dec 23 '16 at 16:52
  • Yes... you can add a string you want for the empty option: http://stackoverflow.com/a/9294117/788509 – bluetoft Dec 23 '16 at 22:39
0

Try this and make sure Model.Status will be the same type as option in foreach

<select class="form-control" asp-for="Status">
        <option></option>
        @foreach (var option in Enum.GetNames(typeof(StatusOptions))) {
            <option value="@option" @{option == Model.Status ? "selected" : ""} }>@option</option>
        }
    </select>
J. Doe
  • 2,651
  • 1
  • 13
  • 31