Asp.net MVC将复选框数据放入布尔列表 [英] Asp.net MVC putting checkbox data in a list of booleans

查看:38
本文介绍了Asp.net MVC将复选框数据放入布尔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将未知数量的复选框绑定到布尔值列表. 经过数小时的搜索,我找不到任何解决方案.

I am trying to bind unknown amount of checkboxes to a list of booleans. After hours of searching I havn't found any solution.

在我看来,这是代码的相关部分:

This is the relevent part of code in my view:

        @foreach (Device d in Data.GetDevices())
    {
        <label asp-for="NewRegistration.Devices">@d.Name</label>
        <input asp-for="NewRegistration.Devices" class="checkbox" type="checkbox" />
    }

循环有效,但是当我更改类型(如果复选框的输入)给了我这种表现的话:

The loop works but when i changed the type if the input to checkbox it gave me this exeption:

InvalidOperationException:意外的'asp-for'表达式结果类型'System.Collections.Generic.List`1 [[System.Boolean,System.Private.CoreLib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = 7cec85d7bea7798e] ]' 为了 .如果类型"为复选框",则"asp-for"的类型必须为"System.Boolean".

InvalidOperationException: Unexpected 'asp-for' expression result type 'System.Collections.Generic.List`1[[System.Boolean, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' for . 'asp-for' must be of type 'System.Boolean' if 'type' is 'checkbox'.

我尝试放入数据的列表包含以下代码:

The list i try to put my data in contains the following code:

        private List<bool> _devices;

    public List<bool> Devices
    {
        get { return _devices; }
        set {_devices = value; }
    }

所以我的问题是如何将这些复选框中的值添加到布尔值列表中.当我不指定输入的类型时,我没有收到任何错误,但是输入的类型是文本.如果我在这些输入框中输入true或false,我的代码就可以正常工作.但是我想要一个复选框,而不是要求用户输入true或false.

So my question is how do I add values from these checkboxes into my list of booleans. When i don't specify the type of the input's, I dont get any errors but the type of the input is text. If i enter true or false in these inputboxes my code works fine. But I want a checkbox instead of asking the user to enter true or false.

谢谢您的时间!

我的问题很难解释.我正在验证表单并将其绑定到表示模型PMRegistration中定义的注册类的实例.如果代码片段不够清晰,我将在下面放置完整的代码

edit: My question proves hard to explain. I'm validating the form and binding it to an instance of the registration class defined in a presentation model PMRegistration. I will put the full code below if the snippets are not clear enough

注册课程:

  public class Registration
{

    public int Id { get; set; }
    [Required(ErrorMessage = "required field")]
    [MaxLength(50, ErrorMessage = "To long")]
    [DisplayName("Name")]
    public string Name { get; set; }
    [Required(ErrorMessage = "required field")]
    [MaxLength(50, ErrorMessage = "To long")]
    [DisplayName("Firstname")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "required field")]
    [Range(1,110 ,ErrorMessage = "To long")]

    public string Age { get; set; }
    [Required(ErrorMessage = "required field")]
    [EmailAddress(ErrorMessage ="Not a valid email address")]
    public string Email { get; set; }
    [Required(ErrorMessage = "required field")]
    [DisplayName("slot1")]
    public int Slot1SessionId { get; set; }
    [Required(ErrorMessage = "required field")]
    [DisplayName("slot2")]
    public int Slot2SessionId { get; set; }
    [Required(ErrorMessage = "required field")]
    [DisplayName("slot3")]
    public int Slot3SessionId { get; set; }


    private List<bool> _devices;

    public List<bool> Devices
    {
        get { return _devices; }
        set {_devices = value; }
    }

    [Required(ErrorMessage = "required field")]
    [DisplayName("Organization")]
    public int OrganizationId { get; set; }
    public bool ClosingParty { get; set; }



}

我的视图如下:

        @using week3.Models;
@model week3.Models.PresentationModels.PMRegistration
<div>
    <h1>New Registration</h1>
    <h2>registration</h2>
</div>
<form class="form-group" asp-controller="Registration" asp-action="New" method="post">
    <div>
        <label asp-for="NewRegistration.Name">Name:</label>
        <input asp-for="NewRegistration.Name" class="form-control" value="@Model.NewRegistration.Name" />
        <span asp-validation-for="NewRegistration.Name" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="NewRegistration.FirstName">Firstname:</label>
        <input asp-for="NewRegistration.FirstName" class="form-control" value="@Model.NewRegistration.FirstName" />
        <span asp-validation-for="NewRegistration.FirstName" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="NewRegistration.Age">Age:</label>
        <input asp-for="NewRegistration.Age" class="form-control" value="@Model.NewRegistration.Age" />
        <span asp-validation-for="NewRegistration.Age" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="NewRegistration.Email">Email:</label>
        <input asp-for="NewRegistration.Email" class="form-control" value="@Model.NewRegistration.Email" />
        <span asp-validation-for="NewRegistration.Email" class="text-danger"></span>
    </div>
    <div>
        <div>Pick your sessions</div>
        <label asp-for="NewRegistration.Slot1SessionId" class="form-label">Slot1:</label>
        <select asp-for="NewRegistration.Slot1SessionId" class="form-control" asp-items="@Model.getSessionNamesBySlot(1)" value="@Model.NewRegistration.Slot1SessionId"></select>
        <span asp-validation-for="NewRegistration.Slot1SessionId" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="NewRegistration.Slot2SessionId">Slot2:</label>
        <select asp-for="NewRegistration.Slot2SessionId" class="form-control" asp-items="@Model.getSessionNamesBySlot(2)" value="@Model.NewRegistration.Slot2SessionId"></select>
        <span asp-validation-for="NewRegistration.Slot2SessionId" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="NewRegistration.Slot3SessionId">Slot3:</label>
        <select asp-for="NewRegistration.Slot3SessionId" class="form-control" asp-items="@Model.getSessionNamesBySlot(3)" value="@Model.NewRegistration.Slot3SessionId"></select>
        <span asp-validation-for="NewRegistration.Slot3SessionId" class="text-danger"></span>
    </div>
    
        <div>are you wearing dangerous accessoires?</div>

        @foreach (Device d in Data.GetDevices())
        {
            
            <label asp-for="NewRegistration.Devices[0]">@d.Name</label>
            <input asp-for="NewRegistration.Devices[0]" class="checkbox" type="checkbox"  />
        }
    <div>
        <label asp-for="NewRegistration.OrganizationId">Organization:</label>
        <select asp-for="NewRegistration.OrganizationId" asp-items="@Model.getOrganizations()" class="form-control"></select><br />
    <span asp-validation-for="NewRegistration.OrganizationId" class="text-danger"></span>
    </div>
    <div>
        <label asp-for="NewRegistration.ClosingParty">Are you coming to the closing party?</label>
        <input asp-for="NewRegistration.ClosingParty" />
        <span asp-validation-for="NewRegistration.ClosingParty" class="text-danger"></span>
    </div>
            <input type="submit" class="btn btn-default" value="Register" />
</form>

推荐答案

错误原因

您的错误是因为您有:asp-for="NewRegistration.Devices".这是无效的,因为标签是类型为checkbox的输入,因此asp-for需要一个布尔值,并且您要向其发送一个布尔值列表.

Your error is because you have this: asp-for="NewRegistration.Devices". That is not valid because the tag is input of type checkbox so asp-for is expecting a boolean and you are sending it a list of booleans.

解决方案

这将为您的设备创建复选框:

This will create checkboxes for your devices:

@foreach (Device d in Data.GetDevices())
{
    @Html.CheckBox(item);
}

但是我的假设是,您希望用户选择这些复选框,然后将其发布回给您,如果是这种情况,那么您需要这样做:

But my assumption is you want the user to select these checkboxes and then post them back to you, if that is the case then you need to do this:

您需要创建一个这样的模型:

You need to create a model like this:

public class Device
{
    public string Name { get; set; }
}
public class DevicesCollectionModel
{
    public List<Device> AvailableDevices { get; set; }
    public List<Device> SelectedDevices { get; set; }
}

填充DevicesCollectionModel.AvailableDevices并将其传递到您的视图. 然后在您的视图中,为AvailableDevices中的每个设备创建一个复选框.请注意下面输入标签的name属性:

Populate the DevicesCollectionModel.AvailableDevices and pass it to your view. Then in your view, create a checkbox for each device in AvailableDevices. Pay attention to the name attribute of the input tag below:

@foreach (var item in Model.AvailableDevices)
{
<div class="checkbox">
    <label>
        <input type="checkbox"
                name="SelectedDevices"
                value="@item.Name" /> @item.Name
        </label>
    </div>
}

然后,在控制器的发布中,您将需要访问SelectedDevices属性,以了解用户选择了什么.

Then in your controller, in post, you will need to access the SelectedDevices property to figure out what the user has selected.

此外,您可以创建单独的模型:一个用于发送给用户,一个控制器从用户那里接收.您传递给视图的模型只能包含AvailableDevices,而您在后期控制器中获得的模型可以具有SelectedDevices. MVC将使用输入标签中的name属性为您绑定它.

Furthermore, you can create separate models: one for sending to the user and one the controller receives from the user. The model you pass to your view can just have the AvailableDevices and the model you get in your controller on post can have SelectedDevices. MVC will bind it for you using the name attribute from the input tag.

这篇关于Asp.net MVC将复选框数据放入布尔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆