You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET MVC控制器中动态设置模型属性值?

Got it, let's break down how to handle your grouped checkbox selections in the ASP.NET MVC POST action and assign the correct items to your 4 CustomPInfo instances, while excluding any individual deselected items. I'll walk you through each part step by step.

1. Define Your Models First

First, let's make sure our models align with the grouped selection logic. I'll assume your existing models look something like this (adjust as needed for your actual schema):

// Represents an individual selectable item
public class PSelect
{
    public int Id { get; set; }
    public string DisplayName { get; set; }
    public int GroupId { get; set; } // Links the item to its parent group
    public bool IsSelected { get; set; } // Tracks if the item is checked
}

// The model you need to populate with selected items
public class CustomPInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<PSelect> SelectedItems { get; set; } = new List<PSelect>();
}

// Helper model to pass grouped items to the view
public class GroupedItemViewModel
{
    public int GroupId { get; set; }
    public string GroupName { get; set; }
    public List<PSelect> ItemsInGroup { get; set; } = new List<PSelect>();
}

2. Build the View with Grouped Checkboxes

Your view will render a table with group-level checkboxes (to select/deselect all items in a group) and individual item checkboxes. Add some JavaScript to sync the group checkbox with its items:

@model List<GroupedItemViewModel>

@using (Html.BeginForm("AssignSelectedItems", "YourController", FormMethod.Post))
{
    <table class="table">
        @foreach (var group in Model)
        {
            <!-- Group header row with select-all checkbox -->
            <tr>
                <td colspan="2">
                    <input type="checkbox" class="group-selector" data-group-id="@group.GroupId" />
                    <strong>@group.GroupName</strong>
                </td>
            </tr>

            <!-- Individual items in the group -->
            @foreach (var item in group.ItemsInGroup)
            {
                <tr>
                    <td style="padding-left: 2rem;">
                        @Html.HiddenFor(m => item.Id)
                        @Html.HiddenFor(m => item.GroupId)
                        @Html.CheckBoxFor(m => item.IsSelected)
                        @Html.LabelFor(m => item.IsSelected, item.DisplayName)
                    </td>
                </tr>
            }
        }
        <tr>
            <td colspan="2">
                <button type="submit" class="btn btn-primary">Save Selections</button>
            </td>
        </tr>
    </table>
}

<script>
    // Sync group checkbox with all items in the group
    document.querySelectorAll('.group-selector').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const groupId = this.dataset.groupId;
            // Find all items in this group and toggle their checked state
            document.querySelectorAll(`input[name*="GroupId"][value="${groupId}"]`)
                .forEach(itemInput => {
                    const itemCheckbox = itemInput.parentElement.querySelector('input[type="checkbox"]');
                    if (itemCheckbox) itemCheckbox.checked = this.checked;
                });
        });
    });
</script>

3. Handle the POST in the Controller

This is the core logic: we'll accept all submitted items, filter out the unselected ones, and assign them to your 4 CustomPInfo instances based on their group ID.

public class YourController : Controller
{
    // GET: Load initial grouped data (replace with your data source)
    public IActionResult Index()
    {
        var groupedData = new List<GroupedItemViewModel>
        {
            new GroupedItemViewModel
            {
                GroupId = 1,
                GroupName = "Group 1 (Custom P1)",
                ItemsInGroup = new List<PSelect>
                {
                    new PSelect { Id = 1, DisplayName = "Item 1-1", GroupId = 1 },
                    new PSelect { Id = 2, DisplayName = "Item 1-2", GroupId = 1 }
                }
            },
            new GroupedItemViewModel
            {
                GroupId = 2,
                GroupName = "Group 2 (Custom P2)",
                ItemsInGroup = new List<PSelect>
                {
                    new PSelect { Id = 3, DisplayName = "Item 2-1", GroupId = 2 },
                    new PSelect { Id = 4, DisplayName = "Item 2-2", GroupId = 2 }
                }
            },
            new GroupedItemViewModel
            {
                GroupId = 3,
                GroupName = "Group 3 (Custom P3)",
                ItemsInGroup = new List<PSelect>
                {
                    new PSelect { Id = 5, DisplayName = "Item 3-1", GroupId = 3 }
                }
            },
            new GroupedItemViewModel
            {
                GroupId = 4,
                GroupName = "Group 4 (Custom P4)",
                ItemsInGroup = new List<PSelect>
                {
                    new PSelect { Id = 6, DisplayName = "Item 4-1", GroupId = 4 }
                }
            }
        };

        return View(groupedData);
    }

    [HttpPost]
    public IActionResult AssignSelectedItems(List<PSelect> submittedItems)
    {
        // Initialize your 4 CustomPInfo instances
        var customP1 = new CustomPInfo { Id = 1, Name = "Custom P1" };
        var customP2 = new CustomPInfo { Id = 2, Name = "Custom P2" };
        var customP3 = new CustomPInfo { Id = 3, Name = "Custom P3" };
        var customP4 = new CustomPInfo { Id = 4, Name = "Custom P4" };

        // Filter selected items by group, excluding unselected ones
        var group1Selected = submittedItems.Where(i => i.GroupId == 1 && i.IsSelected).ToList();
        var group2Selected = submittedItems.Where(i => i.GroupId == 2 && i.IsSelected).ToList();
        var group3Selected = submittedItems.Where(i => i.GroupId == 3 && i.IsSelected).ToList();
        var group4Selected = submittedItems.Where(i => i.GroupId == 4 && i.IsSelected).ToList();

        // Assign filtered items to each CustomPInfo instance
        customP1.SelectedItems = group1Selected;
        customP2.SelectedItems = group2Selected;
        customP3.SelectedItems = group3Selected;
        customP4.SelectedItems = group4Selected;

        // Do your next steps here: save to DB, return confirmation view, etc.
        var allCustomPs = new List<CustomPInfo> { customP1, customP2, customP3, customP4 };
        return View("SelectionResult", allCustomPs);
    }
}

Key Notes

  • Excluding Unselected Items: The Where(i => i.IsSelected) clause ensures only checked items are added to each CustomPInfo's list. If a user deselects an individual item in a group, it won't be included.
  • Model Binding: The List<PSelect> submittedItems parameter works because the view generates form fields with names that match the PSelect properties (thanks to Html.HiddenFor and Html.CheckBoxFor).
  • Group Sync: The JavaScript ensures that checking a group checkbox selects all items in that group, but users can still deselect individual items if needed.

内容的提问来源于stack exchange,提问作者JohnnyBaltimore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:42:32