0
votes

I created an ASP.NET Core 3.1 project. I have a form in it with several checkbox lists. I can get the values into the properties in POST and they are correctly filled in (e.g. List SelectedItems). However for some custom fields I have to do a validation in OnPost() method and if the conditions are not met or a ModelState is not valid, it return Page(). Normally I would expect that every property that was filled in in the form is still filled in, but the checkboxes are always empty and not a single one is checked. The other data (radio buttons, textboxes, etc.) are still filled in.

I even tried to put the values within the Razor page, but even then neither of the checkboxes was checked.

Here is an example of one of the checkboxes: In Razor page:

@for (var i = 1; i <= 10; i++){

 <input name="AreChecked" type="checkbox" id="@i" value="@i" /> @i<br />
 <input type="hidden" value="true" id="@i" name="AreChecked" />}

Behind code:

[BindProperties]
public class TestFormModel : PageModel
{
    [BindProperty]
    public List<int> AreChecked { get; set; }}

public IActionResult OnPost()
    {
       //some other form check statements here
       //...

        if (ModelState.IsValid)
        {
            //process data code...
        }
        return Page();
    }

Can someone help me with this?

1

1 Answers

0
votes

You could use JQuery to achieve as shown :

@page
@model RazorPages3_1.AddimgModelModel

<div class="row">
<div class="col-md-4">
    <form enctype="multipart/form-data" method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Petimg.PetName" class="control-label"></label>
            <input asp-for="Petimg.PetName" class="form-control" />
            <span asp-validation-for="Petimg.PetName" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input asp-for="Uploads" class="form-control" />
        </div>

        @for (var i = 1; i <= 10; i++)
        {
            <input name="AreChecked" type="checkbox" id="@i" value="@i" /> @i<br />
            <input type="hidden" value="true" id="@i" name=""AreChecked" />
            }

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
</div>
</div>

<div>
<a asp-page="Index">Back to List</a>
</div>

@section Scripts {

<script>
  var checkedlist = @Html.Raw(Json.Serialize(Model.AreChecked));;
  if (checkedlist.length > 0) {
    $.each(checkedlist, function (index, value) {
        $('input[type=checkbox]').each(function () {
            var id = $(this).attr("id");
            if (id == value) {
                $(this).attr('checked', 'checked');
            }
        })
    });
  }
</script>
}

Result enter image description here