gpt4 book ai didi

ASP.NET MVC : Use Html. CheckBoxFor() 在选中时收集字符串值列表

转载 作者:行者123 更新时间:2023-12-02 10:55:34 25 4
gpt4 key购买 nike

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

[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>
}

当然,我的 Controller 操作接受表单发布上的模型

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

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

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

谢谢。

最佳答案

您的列表需要是:

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

LicenseIdsToProcess目前是List<string> Html.CheckBoxFor() 无法将字符串值转换为 bool 值。您需要使用字典或列表之类的东西,例如

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>
}

关于ASP.NET MVC : Use Html. CheckBoxFor() 在选中时收集字符串值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com