Home > OS >  How to properly set a selected item in a cshtml view?
How to properly set a selected item in a cshtml view?

Time:10-19

I have this SelectList defined in my ViewModel:

public SelectList AccomodationTypesTypes()
{
    return new SelectList(AccomodationTypes.Select(a => a.Type), "B"); 
}

AccomodationTypes.Select(a => a.Type) is an IENumerable<string> which currently consists of "A", "B", and "C". According to https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.rendering.selectlist.-ctor you can provide a second parameter to indicate the selected value - hardcoded "B" in my case - but that does not work.

If it is any help, this is the snippet in the view that has the SelectList:

<div class="form-group row">
    <label asp-for="Accomodation.AccomodationTypeId" class="col-sm-2 col-form-label">Type</label>
    <div class="col-sm-10"><select asp-for="Accomodation.AccomodationTypeId" asp-items="Model.AccomodationTypesTypes()"></select></div>
</div>

The view displays characteristics of a particular selected Accomodation. AccomodationTypeId is a foreign key to the AccomodationType class, which denotes more general characteristics. In the view the user may select a different AccomodationType for the current Accomodation. When the view is rendered on screen I expect type "B" to be selected, which it currently is not. How can I accomplish this?

CodePudding user response:

I worked it out by using a different overload of SelectList:

public SelectList AccomodationTypesTypes()
{
     return new SelectList(AccomodationTypes, "Id", "Type");
}

"Id" binds with the asp-for (Accomodation.AccomodationTypeId) in the view, and the corresponding "Type" shows in the selection list. Does the trick.

I got off in the wrong direction because return new SelectList(AccomodationTypes.Select(a => a.Type)) already gave me the dropdownlist I wanted, and according to the Microsoft article that I linked I only had to provide a second parameter to establish a selected value ("Id" probably, instead of "B"

  • Related