【问题标题】:ASP.NET MVC: Use Html.CheckBoxFor() to collect list of string values when checkedASP.NET MVC:检查时使用 Html.CheckBoxFor() 收集字符串值列表
【发布时间】:2012-09-29 02:15:27
【问题描述】:

在我的 Web 应用程序中,我有一个页面,其中包含管理员可以批量批准或拒绝的“请求”列表。所以页面看起来像:

[x] Request 1
[ ] Request 2
[x] Request 3
[ ] Request 4

[Approve Selected]   [Deny Selected]

我的模型看起来像:

public class RequestManagementModel
{
    public List<string> LicenseIdsToProcess { get; set; }
    public List<Resource> Resources { get; set; }
    // additional fields
}

在我看来,我有:

int counter = 0;
@foreach (Resource r in Model.Resources)
{
    <tr>
        <td>
            @Html.CheckBoxFor(model => model.LicenseIdsToProcess[counter++], new { value = r.RequestId })
        </td>
    </tr>
}

当然,我的控制器操作接受表单帖子上的模型

public ActionResult ProcessRequests(RequestManagementModel model, ProcessType type)
{
    // process requests here
}

因此,正如您所料,我在 model.LicenseIdsToProcess[counter++] 的视图中收到错误消息,显示“无法将类型 'string' 隐式转换为 'bool'”。它不喜欢我试图使用复选框来表示用户可以从中选择一个或多个值的列表,而不是单个真/假。

我希望这样设置,以便在发布表单时,对于用户选择的每个复选框,该字符串 id 值都绑定到我的模型中的 id 列表。我知道如何通过使用&lt;input type="checkbox"&gt; 来做到这一点,因为我可以在那里设置复选框的值。但是有没有办法将它与 Html.CheckBoxFor 一起使用,通过模型绑定来实现强类型?

谢谢。

【问题讨论】:

    标签: asp.net asp.net-mvc checkbox model-binding


    【解决方案1】:

    您的清单必须是:

    public class RequestManagementModel
    {
        public Dictionary<string, bool> LicenseIdsToProcess { get; set; }
        public List<Resource> Resources { get; set; }
        // additional fields
    }
    

    由于LicenseIdsToProcess 当前是List&lt;string&gt;,Html.CheckBoxFor() 无法将字符串值转换为布尔值。您需要使用字典或列表之类的东西,例如

    public class Licence
    {
        public string Id { get; set; }
        public bool Processed { get;set; }
    }
    
    public class RequestManagementModel
    {
        public List<Licence> LicenseIdsToProcess { get; set; }
        public List<Resource> Resources { get; set; }
        // additional fields
    }
    
    int counter = 0;
    @foreach (Resource r in Model.Resources)
    {
        <tr>
            <td>
                @Html.CheckBoxFor(model => model.License[counter++].Processed, new { value = r.RequestId })
            </td>
        </tr>
    }
    

    或者类似的东西:)

    编辑:

    在回复评论时,我意识到我的代码不正确。这是一个更新的版本:

    @for(int idx = 0; idx < Model.Resources.Count; idx++)
    {
        <tr>
            <td>
                @Html.CheckBoxFor(model => model.License[idx].Processed, new { value = Model.Resources[idx].RequestId })
            </td>
        </tr>
    }
    

    【讨论】:

    • 使用 [counter++] 时出现“表达式不能包含赋值运算符”错误
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多