mardi 7 juillet 2020

Using a checkbox list with Razor Pages for input to DB

I want one of my inputs in a form to come from a list of checkboxes that the user selects. I've been going at this for several hours now, and I still don't understand what I need to do for this. Why is there so much help for MVC on this topic and hardly any for Razor?

.cshtml

<form method="post">
    <label asp-for="ServiceRqLd.JobType" class="control-label"></label>
    <div class="form-check-inline">
        @foreach (var item in Model.JobTypes)
        {
            <input name="AreTypes" type="checkbox" />
        }
    </div>
    <span asp-validation-for="ServiceRqLd.JobType" class="text-danger"></span>
</form>

.cshtml.cs

[BindProperty]
public ServiceRqLd ServiceRqLd { get; set; }
[BindProperty]
public List<string> AreTypes { get; set; }

public IActionResult OnGet()
{
    JobTypes = new List<SelectListItem>()
    {
        new SelectListItem() { Text="Mechanical", Value="Mechanical" },
        new SelectListItem() { Text="Electrical", Value="Electrical" },
        new SelectListItem() { Text="Fluid Power", Value="Fluid Power" },
        new SelectListItem() { Text="Programming", Value="Programming" }
    };

    return Page();
}

Model

public class ServiceRqLd
{
    public int ServiceRqLdID { get; set; }
    public string JobType { get; set; }
}

This is all I have so far, but I have no idea what I'm doing with this. I neither understand how to properly display the list of checkboxes nor know how to set ServiceRqLd.JobType equal to the selected boxes (be it a concatenated string of the selected options or otherwise).

I have received conflicting information on how to do this by setting the name of the checkbox the same or not and how the selected information is stored. Any bit of help would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire