gpt4 book ai didi

c# - 如何在 C# 模型而不是 Controller 中将 bool 值转换为字符串

转载 作者:行者123 更新时间:2023-11-30 19:53:45 26 4
gpt4 key购买 nike

通常,如果我的模型中有一个 bool 字段,那是因为底层数据库有一个位值。然而,我的用户更愿意在 View 中使用是/否而不是真/假或复选框。通常,我在我的 View 模型中将 bool 转换为 string。

我想知道是否可以在数据模型而不是 Controller 中进行这种转换,几年前我已经学会了如何进行。我做了一些研究并尝试从中转换原始字段:

public bool StudentInRoster { get; set; }

对此:

private bool? _studentInRoster;
public string StudentInRoster => _studentInRoster == true ? "Yes" : "No";

但是,ReSharper 给我一个警告:

"field _studentInRoster" is never assigned"

所以我觉得有些地方还是不对。有没有更好的(即正确的)方法来进行这种类型的转换?我需要将数据保存为 bool 值,但将数据显示为是/否。

最佳答案

在数据模型中这样做是个坏主意。ViewModel 是一个正确的地方。

  1. 数据模型负责“如何存储数据(作为位列)”
  2. ViewModel 负责准备显示数据(如字符串/图像/视频等)

关于c# - 如何在 C# 模型而不是 Controller 中将 bool 值转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46670798/

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