【问题标题】:check model value empty or null in javascript在 javascript 中检查模型值是否为空或 null
【发布时间】:2018-08-13 09:25:05
【问题描述】:

这是我的代码

 <script>
 var _getValue = @myViewModel.myInfo.Name == null ? 'isNull' : 'notNull';
 </script>

数据库中@myViewModel.myInfo.Name 的值为空,但此代码始终返回notNull
我怎样才能正确地检查空或空?

【问题讨论】:

  • 您尝试调试它吗?当您在调试会话中检查该属性时,该属性保持什么值?
  • 是的,当我调试时,@myViewModel.myInfo.Name 为 null 。但很奇怪,当我检查 '@myViewModel.myInfo.Name' == '' ? 'isNull' : 'notNull' 时,它返回 isNull

标签: asp.net-mvc asp.net-core ternary-operator isnullorempty


【解决方案1】:

您应该将它添加到带有@ 符号的大括号中

例如

<script>
    var _getValue = '@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")';
</script>

【讨论】:

    【解决方案2】:

    当 Razor 和 javascript 大量混合时会发生这种情况,所以不要养成经常这样做的习惯!

    考虑这一行:

     <script>
     var _getValue = @myViewModel.myInfo.Name == null ? 'isNull' : 'notNull';
     </script>
    

    这里唯一的服务器端 Razor 片段是 @myViewModel.myInfo.Name,它返回 null,它被呈现为一个空字符串。那么客户要做的是:

     <script>
     var _getValue = '' == null ? 'isNull' : 'notNull';
     </script>
    

    现在这个是纯js,在客户端执行,自然给出'notNull'。毕竟,空字符串确实不为空。

    现在考虑一下:

     <script>
     var _getValue = '@myViewModel.myInfo.Name' == '' ? 'isNull' : 'notNull';
     </script>
    

    剃刀片还是一样的,@myViewModel.myInfo.Name,仍然为空,所以去客户端的是:

     <script>
     var _getValue = '' == '' ? 'isNull' : 'notNull';
     </script>
    

    这个时间相等实际上成立,所以你得到的是'isNull'。

    要快速解决此问题,只需遵循evaluate expressions in Razor 的通用语法:

     <script>
     var _getValue = '@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")';
     </script>
    

    现在整个三元组都将在服务器端进行评估。

    接下来,您可能需要查看 String 方法 IsNullOrEmptyIsNullOrWhitespace

    【讨论】:

    • 这个答案也加一个。正如@Nitin 所说,它应该添加在大括号'@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")' 中。
    猜你喜欢
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 2014-08-05
    • 2020-03-16
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多