Search code examples
c#asp.net-corerazor

Problem with Bind Property for Multiselect element


My goal is to create a filterlist where you can choose which schooldays you want to show.

Now I connected the select element via BindProperty to my variable school (see C#-Code below). Everything works fine until I decide not to select anything.

So for example I have previously selected Monday and saved it as a filterlist. After that I decide to change it and uncheck Monday again. Now all the itmes in the Multiselect element are unchecked. However when I click on save. The value of Monday is still stored in the variable school. Otherwise if I uncheck Monday but check Tuesday and save the list, the variable has change to the value of Tuesday.

How can I empty my variable with the BindProperty?

C#

[BindProperty(SupportsGet = true)]
public int[] school { get; set; }

HTML-Code

<div class="form-group col s3">
    <label asp-for="school" class="control-label">Schultage</label>
    <select asp-for="school" class="form-control" asp-items="Model.SchoolDays" multiple > 
    </select>
</div>

Solution

  • It was very strange, in the frontend the value of the select element is empty, but in the backend it wont save as empty.

    So I solved it by setting the variable school in the Post Methode, by using the value of the frontend element. Instead of using the BindProperty.

    HTML

    <div class="form-group col s3">
            <label asp-for="school" class="control-label">Schultage</label>
            <select  asp-for="school" name="schoolDaySelect" class="form-control" asp-items="Model.SchoolDays" multiple ></select>
    </div>
    

    C#

    public async Task<IActionResult> OnPostAsync(int? id , int[] schoolDaySelect)
    {
        school = schoolDaySelect;