Search code examples
c#asp.net-corerazorhtml-selecttag-helpers

<select> tag helper not marking options as "selected" in multiple select


Take the following model:

public class SomeModel
{
    public ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public string Value { get; set; }
}

The model is some kind of object (e.g., a blog entry), that features a list of tags or keywords.

I have a Razor view showing a form to edit a SomeModel object:

@model SomeModel
@{
    // List of available tags is passed by controller
    var tags = (List<Tag>)ViewData["Tags"];
}
<label asp-for="Tags">Tags</label>
<select asp-for="Tags"
        asp-items="@(new SelectList(tags, nameof(Tag.Id), nameof(Tag.Value)))">
</select>

As expected, this generates a multiple select showing the available tags:

<label for="Tags">Tags</label>
<select class="input-validation-error"
        data-val="true" data-val-required="The Tags field is required."
        id="Tags" multiple="multiple" name="Tags">
    <option value="1">tag1</option>
    <option value="2">tag2</option>
</select>

@Model.Tags correctly contains the currently assigned tags; however, the corresponding options are not marked as selected.

How do I fix this behavior?


Solution

  • You need to create a property to pass the selected datas and bind it to the asp-for attribute of select tag.

    Index.cshtml.cs :

    public class IndexModel : PageModel
    {
        [BindProperty]
        public List<int> SelectedTags { get; set; } =  new List<int>{  2, 3 };
        [BindProperty]
        public List<Tag> Tags { get; set; }
        public void OnGet()
        {
            Tags = new List<Tag> {
        new Tag { Id = 1, Value="Mike" },
        new Tag { Id = 2, Value="Pete" },
        new Tag { Id = 3, Value="Katy" },
        new Tag { Id = 4, Value="Carl" } };
    
        }
    }
    

    Index.cshtml:

    @page
    @model WebApplication1_rzaor_page.IndexModel
    @{
        ViewData["Title"] = "SelectTag";
        Layout = "~/Pages/Shared/_Layout.cshtml";
    }
    
    <h1>SelectTag</h1>
    
    <label asp-for="Tags">Tags</label>
    <select asp-for="SelectedTags"
            asp-items="@(new SelectList(Model.Tags, "Id","Value"))">
    </select>

    Result of this demo

    You can refer to this link :Setting Selected Item