【问题标题】:Handling tinyInt booleans with MVC使用 MVC 处理 tinyInt 布尔值
【发布时间】:2014-02-13 17:09:43
【问题描述】:

我有一个 mySQL 表设置,其中有一列数据类型为 TinyInt(1)。这代表一个布尔值。

0 = 假; 1 = 真。

我还建立了一个网站,使用 asp.net 和 MVC 设计向公司展示这些信息。现在,该表将列显示为:

"Are Records Online"| [next column]
------------------------------------
 1                  |   junk
 1                  |    junk
 0                  |  junk

但是,我希望 1 和 0 显示为“真/假”或“是/否”。基本上只是更用户友好的东西。

我应该怎么做?使用视图页面本身的脚本或控制器中的 foreach 循环,例如:

foreach(ListViewModel i in DefaultList)
            {
               if(i.RecordsOnline == true)
                {  //set to 'yes'
                 }
                else if(i.RecordsOnline = false)
                { //set to 'no'
                }
            }

【问题讨论】:

    标签: mysql asp.net-mvc c#-4.0 boolean


    【解决方案1】:

    只需使用一个简单的三元组在您的视图中打印适当的文本位:

    @(i.RecordsOnline ? "Yes" : "No")
    

    【讨论】:

      【解决方案2】:

      您可以使用类型ENUM('yes', 'no') 代替TINYINT。相同的每个值一个字节,但更加用户友好。

      【讨论】:

        【解决方案3】:

        您可以基于 bool 类型创建 DisplayTemplate,因为您似乎在模型中将 tinyint 转换为 bool。

        -- YesNo.cshtml
        @model bool
        
        @(Model ? "Yes" : "No")
        

        将该文件夹放在 ~/Views/Shared/DisplayTemplates 中

        你可以这样使用它:(假设 RecordsOnline 是你模型的一部分并且是一个布尔值)

        @Html.DisplayFor(m => m.RecordsOnline, "YesNo")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-09
          • 2017-03-05
          • 1970-01-01
          • 2011-04-14
          • 1970-01-01
          • 2011-11-25
          相关资源
          最近更新 更多