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>
1
  • You do not set the selected property. The Tag Helper does that based on the value of the property you binding to. - <select asp-for="Status" asp-items="Html.GetEnumSelectList<StatusOptions>()"></select> Commented Dec 20, 2016 at 21:16

2 Answers 2

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.

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

2 Comments

Is there a way to add an empty first option to that helper or does it need to be injected into the StatusOptions list?
Yes... you can add a string you want for the empty option: stackoverflow.com/a/9294117/788509
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>

Comments

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.