Search code examples
asp.net-corerazor-pages

Stop ASP.NET Core razor page from rending muti-select list box


I am using tag helpers to generate a form in my ASP.NET Core 7 Razor pages project. I have created a SelectList that I only want a single option to be selected from but when it gets rendered out instead of a drop down list I get a multi-select box. What am I doing wrong/missing to get it to rending a normal drop-down?

Get data from database:

public async Task<IEnumerable<NameIDPairDTO>> GetSectionList()
{
    return await _siteDbContext.Sections
                               .OrderBy(s => s.Title)
                               .Select(s => new NameIDPairDTO()
                                       {
                                           ID = s.ID,
                                           Name = s.Title
                                       }).ToListAsync();
}

Page code behind:

public class ManageSectionModel : PageModel
{
    private readonly ISectionHelper _sectionHelper;

    public ManageSectionModel(ISectionHelper sectionHelper)
    {
        _sectionHelper = sectionHelper;
    }

    public SelectList ExistingSections { get; private set; }

    public async Task<IActionResult> OnGetAsync()
    {
        var secitons = await _sectionHelper.GetSectionList();
        ExistingSections = new SelectList(secitons, "ID", "Name");
        return Page();
    }
}

Markup in the front end to render select list:

<select asp-for="ExistingSections" asp-items="Model.ExistingSections">
    <option value="0">Add New Section</option>
</select>

Solution

  • The asp-for attribute should reference the property that will hold the selected value, not the collection that you bind to the asp-items attribute. If the selected value is a single property, not a collection, the tag helper won't render the multiple attribute.

    public class ManageSectionModel : PageModel
    {
        private readonly ISectionHelper _sectionHelper;
    
        public ManageSectionModel(ISectionHelper sectionHelper)
        {
            _sectionHelper = sectionHelper;
        }
    
        public SelectList ExistingSections { get; private set; }
        [BindProperty]
        public int SelectedSection { get; set; }
        public async Task<IActionResult> OnGetAsync()
        {
            var secitons = await _sectionHelper.GetSectionList();
            ExistingSections = new SelectList(secitons, "ID", "Name");
            return Page();
        }
    }
    
    <select asp-for="SelectedSection" asp-items="Model.ExistingSections">
        <option value="0">Add New Section</option>
    </select>