ASP.NET MVC Get checkstate from looped, bound checkboxes

79 views Asked by At

in my journey of learning ASP.NET MVC I encounterd another difficulty:

I'm trying to POST a form with 3 checkboxes, the checkboxes are looped onto the form according to a bound PresentationModel.

I don't know what to fill in at the "asp-for" tag-helpers for the checkboxes in the view so they pass a boolean to the "Create()" ActionResult in the controller and to show the values in the "Overview" View.

Currently it passes NULL for al of them, the other aproaches I tried always resulted in an "InvalidCastException" as it has to be a boolean not an "int[]".

PresentationModel (PMRegistration.cs)

public class PMRegistration
{
    public List<Device> Devices { get; set; }
}

View (Index.cshtml)

@model Week3_oef2_ITPro.PresentationModel.PMRegistration
<form asp-controller="Register" asp-action="Create" method="post">
<table>
    <tr>
        <td>Are you wearing any dangerous accessoires</td>
    </tr>
    @foreach (var item in Model.Devices)
    {
        <tr>
            <td>@item.Name</td>
            <td class="form-group">
                <input type="checkbox" asp-for="@item.CheckState" value="@item.Id"  class="form-control" />
            </td>
        </tr>
    }
    <tr>
        <td>
            <input type="submit" class="btn btn-default" />
        </td>
    </tr>
</table>
</form>

Model (Device.cs)

public class Device
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool CheckState { get; set; }
}

Model (Data.cs, the Device objects get initialized here)

    private static List<Device> devices = new List<Device>();

    static Data()
    {
        devices.Add(new Device() { Id = 1, Name = "Laptop" });
        devices.Add(new Device() { Id = 2, Name = "Tablet" });
        devices.Add(new Device() { Id = 3, Name = "Apple Watch" });
    }

    public static List<Device> GetDevices()
    {
        return devices;
    }

Controller (RegisterController.cs)

public class RegisterController : Controller
{
    // GET: /<controller>/
    [HttpGet]
    public IActionResult Index()
    {
        PMRegistration pm = new PMRegistration();

        pm.Devices = Data.GetDevices();

        return View(pm);
    }
    public ActionResult Create(PMRegistration pm)
    {
        if (ModelState.IsValid)
        {
            return View("Overview", pm);
        }
        else
        {
            return RedirectToAction("Index");
        }
    }
}

------------ SOLVED -------------

With HTML-helpers:

@for (int i = 0; i < Model.Devices.Count; i++)
    {
        <tr>
            <td>
                @Model.Devices[i].Name
            </td>
            <td>
                @Html.CheckBoxFor(m => Model.Devices[i].CheckState)
                @Html.HiddenFor(m => Model.Devices[i].Id)
                @Html.HiddenFor(m => Model.Devices[i].Name)
            </td>
        </tr>
    }
0

There are 0 answers