asp.net-coredata-bindingrazor-pagesmulti-selectselectlist

Cant Figure out what goes wrong in model binding ASP.NET Core + Razor Pages


I'm trying to simply get my selected items populated to the bound property SelectedDataSourceIDs, but I can't figure out what I'm doing wrong.

The view:

@page

@model ContosoUniversity.Pages.Analysis.IndexModel
@{
}

<h1>Analysis</h1>
<form asp-page-handler="Analyze" method="post">
    <div class="form-group">
        <label asp-for="SelectedDataSourcesIDs" class="control-label"></label>
        <select asp-for="SelectedDataSourceIDs" class="form-control" asp-items="@Model.DataSourceNameSL" multiple>
        </select>
        <span asp-validation-for="SelectedDataSourceIDs" class="text-danger" />
    </div>
    <div class="form-group">
        <input type="submit" value="Analyze" class="btn btn-primary" />
    </div>
</form>

The model class:

public class IndexModel : DataSourceResourcesCompaniesSelectListModel
{
    private readonly ContosoUniversity.Data.SchoolContext _context;
    public IEnumerable<int> SelectedDataSourceIDs { get; set; }
    private AnalysisContext _analysisContext;

    public IActionResult OnGet()
    {
        PopulateDataSourceDropDownList(_context);
        return Page();
    }

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
    }
}

I have a breakpoint in OnPost and SelectedDataSourceIDs is always null.

What I tried/tested

  1. In OnGet(), the DataSourceNameSL is correctly populated with DataTextField = "Name" and DataValueField = "ID". I can see and select multiple ListItems

  2. In the payload of the query, there are the IDs

  3. The naming is correct

  4. The ModelState is valid

  5. In OnPost(), the DataSourceNameSL is null and SelectedDataSourceIDs is null

  6. I've even tried changing the Type from IEnumerable<int> to List<int>

What am I doing wrong?


Solution

  • Add the [BindProperty] attribute when dealing with model-binding in razor app.

    [BindProperty]
    public IEnumerable<int> SelectedDataSourceIDs { get; set; }
    

    enter image description here