3

在我的 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 列表。我知道如何通过使用来做到这一点<input type="checkbox">,因为我可以在那里设置复选框的值。但是有没有办法将它与 Html.CheckBoxFor 一起使用,通过模型绑定来实现强类型?

谢谢。

4

1 回答 1

4

您的清单必须是:

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

由于LicenseIdsToProcess目前是List<string>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>
}
于 2012-10-08T19:45:02.140 回答