【问题标题】:Why ViewBag if condition not working in Jquery? [closed]如果条件在 Jquery 中不起作用,为什么要使用 ViewBag? [关闭]
【发布时间】:2020-10-11 02:48:29
【问题描述】:

我正在尝试在 jquery 中检查 ViewBag。看来它的工作。我添加了console.log 和alert 都不起作用。我的代码有什么问题?

     /* Begin- Here we check if member credit card blocked */
        bool isCCBlocked = membershipRenewal.CheckCCDeniedDemographic(memberId);
        ViewBag.IsCCBlocked = isCCBlocked?"true":"false";
     /* End- Here we check if member credit card blocked */

jQuery

 $(document).ready(function () {
        // Checking if member credit card blocked    
        if (@ViewBag.IsCCBlocked.ToString().ToLower()==="true") {
            alert("IsCCBlocked");
        }
});

【问题讨论】:

  • 您只是漏掉了引号。试试这个if ("@ViewBag.IsCCBlocked?.ToString()?.ToLower()" === "true") {
  • 或者if (@ViewBag.IsCCBlocked.ToString().ToLower())呢? IE。 if(true)
  • 遇到这些问题,第一步是总是在浏览器中到View Source。
  • 试试这个: if ('@ViewBag.IsCCBlocked'=='True') { alert("IsCCBlocked"); }

标签: c# jquery asp.net-mvc


【解决方案1】:

您可以在 .cshtml 文件中包含服务器端代码...服务器端代码必须以 @ 符号开头...当您运行程序时,服务器端代码在服务器上执行,然后页面被渲染成一个 HTML 文件发送给客户端...

由于您要将@ViewBag 的内容转换为字符串,因此需要将其放在引号中(因为字符串在.js 中被引用),因此您需要这样的内容:

// this will generate something like: var isCCBlocked = 'true'; 
var isCCBlocked = '@ViewBag.IsCCBlocked.ToString().ToLower()'; 
if (isCcBlocked === "true") {
    alert("IsCCBlocked");
}

【讨论】:

    猜你喜欢
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多