ASP.NET MVC从循环,绑定复选框获取checkstate

时间:2017-01-03 19:14:47

标签: c# asp.net asp.net-mvc checkbox tag-helpers

在我学习ASP.NET MVC的过程中,我遇到了另一个困难:

我尝试 POST 一个带有3个复选框的表单,根据绑定的PresentationModel将复选框循环到表单上。

我不知道在" asp-for" tag-helpers 用于视图中的复选框,以便将布尔值传递给" Create()" ActionResult在控制器中显示"概述"图。

目前它为其中的一个传递NULL,我试过的其他方法总是导致" InvalidCastException"因为它必须是布尔值而不是" int []"。

PresentationModel(PMRegistration.cs)

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

查看(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>

模型(Device.cs)

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

模型(Data.cs,Device对象在这里初始化)

    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");
        }
    }
}

------------ 已解决 -------------

使用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 个答案:

没有答案