如何在ASP中实现一个复选框列表?净的核心

本文关键字:列表 复选框 一个 核心 ASP 实现 | 更新日期: 2023-09-27 18:17:26

我希望在ASP中实现一个复选框列表。. NET Core,但我面临一些困难。

我的视图模型:

public class GroupIndexViewModel
{
    public Filter[] Filters { get; set; }
}
public class Filter
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Selected { get; set; }
}

我的观点:

@model GroupIndexViewModel
<form asp-action="Index" asp-controller="Group" method="get">
  <ul>
  @for (var i = 0; i < Model.Filters.Length; i++)
  {
    <li>
      <input type="checkbox" id="@Model.Filters[i].Name" asp-for="@Model.Filters[i].Selected" value="@Model.Filters[i].Selected" checked="@Model.Filters[i].Selected" />
      <label for="@Model.Filters[i].Name">@Model.Filters[i].Name</label>
    </li>
  }
  </ul>
  <button type="submit" name="action">Filtrer</button>
</form>

当发布到我的控制器时,我的viewmodel中的Filter属性显示被选中的false,即使它在视图中被选中。

如何在ASP中实现一个复选框列表?净的核心

我会这样做。

@model GroupIndexViewModel
<form asp-action="Index" asp-controller="Group" method="get">
    <ul>
        @for (var i = 0; i < Model.Filters.Count; i++)
        {
            <li>       
                <input type="checkbox" asp-for="@Model.Filters[i].Selected"  />
                <label asp-for="@Model.Filters[i].Selected">@Model.Filters[i].Name</label>
                <input type="hidden" asp-for="@Model.Filters[i].Id" />
                <input type="hidden" asp-for="@Model.Filters[i].Name" />                
            </li>
        }
    </ul>
    <button type="submit" name="action">Filtrer</button>
</form>

这里我假设你有适当的控制器和动作的实现

这个问题可能已经有答案了,但是我想解释一下你的问题,这样别人就能明白发生了什么。

您没有意识到您已经为您的输入指定了false值,因为您正在实现对属性的错误使用。

让我们看看你的视图

@model GroupIndexViewModel
<form asp-action="Index" asp-controller="Group" method="get">
   <ul>
     @for (var i = 0; i < Model.Filters.Length; i++)
     {
      <li>
        <input type="checkbox" id="@Model.Filters[i].Name" asp-for="@Model.Filters[i].Selected" value="@Model.Filters[i].Selected" checked="@Model.Filters[i].Selected" />
        <label for="@Model.Filters[i].Name">@Model.Filters[i].Name</label>
     </li>
     }
  </ul>
  <button type="submit" name="action">Filtrer</button>
</form>

,第一。您正在从Filter数组中创建输入元素。现在让我们仔细看看输入元素。

<input type="checkbox" id="@Model.Filters[i].Name" asp-for="@Model.Filters[i].Selected" value="@Model.Filters[i].Selected" checked="@Model.Filters[i].Selected" />

现在,让我解释一下。

  1. 使用type属性指定类型。
  2. 您正在使用id属性指定id。
  3. 使用asp-for标签助手将输入绑定到模型。
  4. 使用value属性为输入指定一个值。
  5. 最后,使用checked属性将输入设置为checked。

如果你看一下标签助手文档,你会发现之间的关系。Net类型输入类型,理解:

复选框保存一个布尔值,与模型相对应,并由标签助手格式化为type="checkbox"

因为您使用的是type="checkbox"属性,所以标签助手值只能是truefalse。如果我们回头看一下输入元素,你已经给输入指定了一个值。尽管标记帮助器可以为输入赋值,但它不能覆盖已经指定的值。因此,您的输入将始终具有您指定的值,在本例中,boolean默认为始终为false

现在您可能认为您的输入元素具有false值,例如,添加checked="checked" 将不会将值更改为true,因为value属性覆盖了checked属性。导致两个属性的错误实现。 因此,您只能使用中的一个属性。(valuechecked)。为了方便,你可以使用它们。但是在这种情况下,必须使用默认的checked属性。由于您正在实现标记助手,并且输入值必须为boolean类型。checked属性值返回一个布尔值,例如,它是标签助手使用的值。

所以@dotnetstep提供的实现应该可以工作,因为它只在输入元素中声明标记帮助器。因此,标签助手自己处理输入的相应属性。

@model GroupIndexViewModel
<form asp-action="Index" asp-controller="Group" method="get">
    <ul>
        @for (var i = 0; i < Model.Filters.Count; i++)
        {
            <li>       
                <input type="checkbox" asp-for="@Model.Filters[i].Selected"  />
                <label asp-for="@Model.Filters[i].Selected">@Model.Filters[i].Name</label>
                <input type="hidden" asp-for="@Model.Filters[i].Id" />
                <input type="hidden" asp-for="@Model.Filters[i].Name" />                
            </li>
        }
    </ul>
    <button type="submit" name="action">Filtrer</button>
</form>

基于@dotnetstep的回答,我创建了一个标签助手,它接受SelectListItem的IEnumerable模型,并生成他的回答中描述的字段。

标签助手代码:

[HtmlTargetElement(Attributes = "asp-checklistbox, asp-modelname")]
public class CheckListBoxTagHelper : TagHelper
{
    [HtmlAttributeName("asp-checklistbox")]
    public IEnumerable<SelectListItem> Items { get; set; }
    [HtmlAttributeName("asp-modelname")]
    public string ModelName { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var i = 0;
        foreach (var item in Items)
        {
            var selected = item.Selected ? @"checked=""checked""" : "";
            var disabled = item.Disabled ? @"disabled=""disabled""" : "";
            var html = $@"<label><input type=""checkbox"" {selected} {disabled} id=""{ModelName}_{i}__Selected"" name=""{ModelName}[{i}].Selected"" value=""true"" /> {item.Text}</label>";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Value"" name=""{ModelName}[{i}].Value"" value=""{item.Value}"">";
            html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Text"" name=""{ModelName}[{i}].Text"" value=""{item.Text}"">";
            output.Content.AppendHtml(html);
            i++;
        }
        output.Attributes.SetAttribute("class", "th-chklstbx");
    }
}

您将需要向_ViewImports添加以下内容。cshtml文件:

@addTagHelper *, <ProjectName>

然后将复选框放入razor视图中,只需:

<div asp-checklistbox="Model.Brands" asp-modelname="Brands"></div>

你可能会注意到,我添加了一个类属性的div样式框及其内容。下面是CSS:

.th-chklstbx {
  border: 1px solid #ccc;
  padding: 10px 15px;
  -webkit-border-radius: 5px ;
  -moz-border-radius: 5px ;
  -ms-border-radius: 5px ;
  border-radius: 5px ; 
}
.th-chklstbx label {
    display: block;
    margin-bottom: 10px; 
}

站在@dotnetstep和@gsxrboy73的肩膀上,这种方法添加了一个可选的控件标题和"Check All"复选框的类型。它还序列化"id"属性,以便您可以安全地在页面上拥有多个复选框列表。这是为。net 5在Bootstrap环境中绑定到MVC模型而定制的。

我更喜欢轻薄的模型,不需要庞大的mvc库:

public class CheckBoxListItem
{
    public string Key { get; set; }
    public string Value { get; set; }
    public bool IsChecked { get; set; } = false;
    public bool IsDisabled { get; set; } = false;
}

一个List<CheckBoxListItem>驱动标签助手:

/// <summary>check-box-list Tag Helper</summary>
[HtmlTargetElement("Check-Box-List", Attributes = "asp-title, asp-items, asp-model-name, asp-check-all-label", TagStructure=TagStructure.NormalOrSelfClosing)]
public class CheckBoxListTagHelper : TagHelper
{
    /// <summary>HTML element ID of the tracking form element</summary>
    [HtmlAttributeName("asp-form-id")]
    public string FormId { get; set; }
    /// <summary>Optional bolder title set above the check box list</summary>
    [HtmlAttributeName("asp-title")]
    public string ListTitle { get; set; }
    /// <summary>List of individual child/item values to be rendered as check boxes</summary>
    [HtmlAttributeName("asp-items")]
    public List<CheckBoxListItem> Items { get; set; }
    /// <summary>The name of the view model which is used for rendering html "id" and "name" attributes of each check box input.
    /// Typically the name of a List[CheckBoxListItem] property on the actual passed in @Model</summary>
    [HtmlAttributeName("asp-model-name")]
    public string ModelName { get; set; }
    /// <summary>Optional label of a "Check All" type checkbox.  If left empty, a "Check All" check box will not be rendered.</summary>
    [HtmlAttributeName("asp-check-all-label")]
    public string CheckAllLabel { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        string id = context.UniqueId;
        output.TagName = "div";
        string html = "";
        output.PreElement.AppendHtml($"<!-- Check List Box for {(string.IsNullOrEmpty(ListTitle) ? ModelName : ListTitle)} -->'r'n");
        if (!string.IsNullOrEmpty(ListTitle))
        {
            // Prepend a Title to the control
            output.PreContent.AppendHtml($"'r'n't<label id='"check-box-list-label-{id}'" class='"cblTitle'">'r'n"
                + $"'t't<strong>{ListTitle}</strong>'r'n"
                + $"'t</label>'r'n");
        }
        if (!string.IsNullOrEmpty(CheckAllLabel))
        {
            // Prepend a "Check All" type checkbox to the control
            output.PreContent.AppendHtml("'t<div class='"form-check'">'r'n"
                + $"'t't<input id='"check-box-list-all-{id}'"'r'n"
                + "'t't'tclass='"cblCheckAllInput form-check-input'"'r'n"
                + "'t't'ttype='"checkbox'"'r'n"
                + $"'t't'tvalue='"true'"'r'n"
                );
            if (Items.All(cbli => cbli.IsChecked))
            {
                output.PreContent.AppendHtml("'t't'tchecked='"checked'"'r'n");
            }
            output.PreContent.AppendHtml("'t't't/>'r'n"
                + $"'t't<label id='"check-box-list-all-label-{id}'" class='"cblCheckAllLabel form-check-label'" for='"check-box-list-all-{id}'">'r'n"
                + $"'t't't&nbsp; {CheckAllLabel}'r'n"
                + "'t't</label>'r'n"
                + "'t</div>'r'n"
                ) ;
        }
        // Begin the actual Check Box List control
        output.Content.AppendHtml($"'t<div id='"cblContent-{id}'" class='"cblContent'">'r'n");
        // Create an individual check box for each item
        for (int i = 0; i < Items.Count(); i++)
        {
            CheckBoxListItem item = Items[i];
            html = "'t't<div class='"form-check'">'r'n"
                + $"'t't't<input id='"{ModelName}_{i}__IsChecked-{id}'"'r'n"
                + $"'t't't'tname='"{ModelName}[{i}].IsChecked'"'r'n"
                + $"'t't't'tclass='"cblCheckBox form-check-input'"'r'n"
                + $"'t't't'tform='"{FormId}'"'r'n"
                + "'t't't'tdata-val='"true'"'r'n"
                + "'t't't'ttype='"checkbox'""
                + "'t't't'tvalue='"true'""
                ;
            if (item.IsChecked)
            {
                html += "'t't't'tchecked='"checked'"'r'n";
            }
            if (item.IsDisabled)
            {
                html += "'t't't'tdisabled='"disabled'"'r'n";
            }
            html += "'t't't't/>'r'n"
                + $"'t't't<label id='"check-box-list-item-label-{id}-{i}'" class='"cblItemLabel form-check-label'" for='"{ModelName}_{i}__IsChecked-{id}'">'r'n"
                + $"'t't't't&nbsp; {item.Value}'r'n"
                + "'t't't</label>'r'n"
                + $"'t't't<input type='"hidden'" id='"{ModelName}_{i}__IsChecked-{id}-tag'" name='"{ModelName}[{i}].IsChecked'" form ='"{FormId}'" value='"false'">'r'n"
                + $"'t't't<input type='"hidden'" id='"{ModelName}_{i}__Key-{id}'" name='"{ModelName}[{i}].Key'" form ='"{FormId}'" value='"{item.Key}'">'r'n"
                + $"'t't't<input type='"hidden'" id='"{ModelName}_{i}__Value-{id}'" name='"{ModelName}[{i}].Value'" form ='"{FormId}'" value='"{item.Value}'">'r'n"
                + "'t't</div>'r'n"
                ;
            output.Content.AppendHtml(html);
        }
        output.Content.AppendHtml("'t</div>'r'n");
        output.Attributes.SetAttribute("id", $"check-box-list-{id}");
        output.Attributes.SetAttribute("class", "cblCheckBoxList");
    }
}

显示原型JS使"Check All"Box play nice with others:

// Attach event handlers to controls
$(function () {
    // Toggle child check boxes per the "Check All" check box state
    $("div.cblCheckBoxList").on("click", "input.cblCheckAllInput", function (event) {
        let chkBoxListDiv = $(event.target).closest("div.cblCheckBoxList");
        let chkBoxList = new checkBoxList($(chkBoxListDiv).attr("id"), $(event.target).attr("id"));
        chkBoxList.onCheckAllClick();
    });
    // Sync the "Check All" box w/ the child check boxes' check box states
    $("div.cblCheckBoxList").on("click", "input.cblCheckBox", function (event) {
        let chkBoxListDiv = $(event.target).closest("div.cblCheckBoxList");
        let chkBoxList = new checkBoxList($(chkBoxListDiv).attr("id"), null);
        chkBoxList.onCheckItemClick();
    });
});

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Check Box List
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var checkBoxList = function (checkBoxListDivId, checkAllInputId) {
    this.listDivId = checkBoxListDivId;
    this.allInputId = (checkAllInputId ?? $("#" + this.listDivId).find("input.cblCheckAllInput")?.first()?.attr("id"));
};
checkBoxList.prototype = function () {
    // If a "Check All" type check box is clicked, update the individual child check boxes accordingly
    var onCheckAllClick = function () {
        // Find the "Check All" check box that was clicked
        let checkAllInput = $('#' + this.allInputId);
        // Determine whether the "Check All" check box is checked or unchecked
        let chkd = $(checkAllInput).prop('checked');
        // Get a list of child/item check boxes
        let chks = $('#' + this.listDivId).find('input.cblCheckBox');
        // Make the child/item check boxes match the value of the "Check All" check box
        chks.prop('checked', chkd);
    },
    // If an individual child check box is clicked and a "Check All" type checkbox exists, update it accordingly
    onCheckItemClick = function () {
        if (!((this.allInputId === undefined) || (this.allInputId.length === 0))) {
            // Get an array of check boxes that are NOT checked
            let notChkd = $('#' + this.listDivId).find("input.cblCheckBox:not(:checked)");
            // Update the "Check All" check box accordingly
            $("#" + this.allInputId).prop('checked', (notChkd.length === 0));
        }
    };
    return {
        onCheckAllClick: onCheckAllClick,
        onCheckItemClick: onCheckItemClick
    };
}();

给CSS涂上口红:

/*  For CheckBoxList form control   */
.cblCheckBoxList {
    border: 1px solid #ccc;
    padding: 10px 15px;
    margin-right: 10px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    border-radius: 5px;
}
    .cblCheckBoxList .cblContent {
        height: 150px;
        overflow-y: scroll;
        padding: 0;
        margin: 0;
    }
    .cblCheckBoxList .cblTitle {
        font-weight: bolder;
    }
    .cblCheckBoxList .cblCheckAllLabel {
        margin-bottom: 10px;
    }
    .cblCheckBoxList .cblCheckAllInput {
        margin-bottom: 0;
    }
    .cblCheckBoxList .cblItemLabel {
        margin-bottom: 0;
        font-size: small;
    }
    .cblCheckBoxList .cblCheckBox {
        margin-bottom: 0;
        font-size: small;
    }

并将复选框列表放到页面上:

@* On the passed in View Model, "IceCreamFlavors" is a property that is a List of type CheckBoxListItem *@
<check-box-list 
    asp-title="Ice Cream Flavors"
    asp-items="Model.IceCreamFlavors"
    asp-model-name="IceCreamFlavors"
    asp-form-id="my-form-id"
    asp-check-all-label="All Flavors"
    >
</check-box-list>

Botta boom, Botta bing。

我刚刚试了一下,它工作了:

<input asp-for="filter.type[i].IsEnabled"/>

不带复选框,然后对应的布尔值在模型中隐藏id和名称