Home > Blockchain >  asp.net core <select> with tag-helpers, make a specif <option> tag be selected
asp.net core <select> with tag-helpers, make a specif <option> tag be selected

Time:05-03

I'm using ASP.NET Core, with .NET 6.

I have a view model:

class SomeModel {
 
    public int SelectedProjectId {get; set; } // This is the current project.
    // Some more properties.
 
}

My select:

 <select asp-for="ProjectId" asp-items="@(new SelectList(projects, nameof(Project.ProjectId), nameof(Project.Name)))"></select>

This works fine, but my problem is, the select is used to edit existing data, so how can I make sure the option-tag with the value of SelectedProjectId is selected?

CodePudding user response:

According to the code you shared, try the following...

<select asp-for="ProjectId" asp-items="@(new SelectList(projects, nameof(Project.ProjectId), nameof(Project.Name), SomeModel.SelectedProjectId))"></select>

You add a third parameter to SelectList with the selected value.

Here is the reference of SelectList constructors:

https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#system-web-mvc-selectlist-ctor(system-collections-ienumerable-system-string-system-string-system-object)

  • Related