【问题标题】:ASP.NET MVC - map bools in View to List of ints in ViewModelASP.NET MVC - 将视图中的布尔映射到视图模型中的整数列表
【发布时间】:2020-05-04 21:14:45
【问题描述】:

我们有一套系统来管理英国建筑工匠的各个方面。

我们正在添加一个新部分来管理他们的认证,并希望简化我们当前的实施。

我们希望在 ViewModel 中有一个List<int>,但不确定如何从 View 中写入。请参阅下面的伪视图代码中的问题:

如果有帮助,我们会使用剑道。

视图模型

AccreditationApprovalViewModel.cs

public class AccreditationApprovalViewModel : ApprovalViewModel
{
    // currently have:
    // public bool HasAccreditation1;
    // public bool HasAccreditation2;
    // …
    // public bool HasAccreditationN;

    // We want to change the individual bools above to:
    [DisplayName(“Has Accreditation“)]
    public List<int> HasAccreditations;
}

查看

AccreditationApproval.cshtml

这里有许多布尔标志控件:

  • Accreditation1Flag

    • 如果设置为 true,则 int 1 将添加到 ViewModel 中的 HasAccreditations 列表中(如果尚未在列表中)
    • 如果设置为 false,则 int 1 将从 ViewModel 中的 HasAccreditations 列表中删除
  • Accreditation2Flag

    • 如果设置为 true,则 int 2 将添加到 ViewModel 中的 HasAccreditations 列表中(如果尚未在列表中)
    • 如果设置为 false,则 int 2 将从 ViewModel 中的 HasAccreditations 列表中删除

认证 3、4、5 等类似

我们的两个问题是:

  • 我们如何创建 EditorFor 条目,以允许它写入 ViewModel 中的 List&lt;int&gt;
  • 我们如何将数字连接到 LabelFor 中的 DisplayString?
@Html.LabelFor(model => model.HasAccreditations.Concat(" 1"))
@Html.EditorFor(model => model.HasAccreditations[0]) @* bool control writing to int in array *@    

@Html.LabelFor(model => model.HasAccreditations.Concat(" 2"))
@Html.EditorFor(model => model.HasAccreditations[1]) @* bool control writing to int in array *@

【问题讨论】:

  • 您的实际问题是什么?我在这里看不到它。如果您有很多认证,我不会将它们存储在单独的 bools 中。在查找表中给每个人一个 ID 并创建多对多连接。
  • 乔纳森,我已经修改了我的帖子,以便更清楚地了解我的问题。我们目前将我们的认证存储在个人bools 中,但希望它们位于列表中。我们不确定视图中会发生什么

标签: c# asp.net asp.net-mvc razor


【解决方案1】:

我认为你应该重组你的模型,否则你将永远来回翻译,你将无法轻易添加新的认证类型等。

一人一桌。带有人员 ID 和认证 ID 的多对多中间表。以及一个带有认证 ID 和认证标题的认证新表。

如果您使用实体框架或类似框架,正确连接的表将轻松公开所有相关属性,以便构建您的模型/视图模型。

对于您的观点,您正在使用剑道,您可以使用他们的多重选择器,或一系列以认证 id 作为值和认证标题作为标签的复选框。

【讨论】:

  • 感谢您的回答,@Jonathan。如果我们必须重写这个,我们肯定会按照您的建议重新构建模型,但我们没有资源在这个版本上这样做。对于这个版本,我们只是希望我们可以编写一些 javascript 来将单个 bool 转换为 int 集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 2017-07-29
  • 1970-01-01
相关资源
最近更新 更多