Razor:在 JavaScript 块中用 C# 声明字符串时预期";"



在下面的MVC View代码中,isLoggedInDb以绿色下划线显示,工具提示显示预期的";"。 显然有一个;,很难谷歌搜索;在它之上。 我已经看到其他人在以这种方式创建 JavaScript 服务器端时遇到问题,所以也许这不是最佳实践。 应该忽略这一点,还是有正当理由让智能感知抱怨?

@* SHTML Code Above *@
<script type="text/javascript">
    @{  
        string isLoggedInDb;
        if(Session["isLoggedInDb"] != null)
        {
            if(Session["isLoggedInDb"].ToString() == "1") 
            {
                isLoggedInDb = "1";
            }
            else
            {
                isLoggedInDb = "0";
            }
        }
    }
    var dblogin=@(isLoggedInDb);
    @*....etc*@
    }

编辑

我突然想到,以编程方式构建 JavaScript 可能不是最好的主意,因为将 JavaScript 保存在单独的文件中可能被认为是最佳实践,这些文件通常是缓存的。 我想我应该在JavaScript读取的HTML中编写隐藏变量。 也许有人可以证实这一点。

我不是 100% 确定,但我认为编译器将其视为 C# 代码,因为您将其放在 Razor 代码块中@{ }

试试这个:

<script type="text/javascript">
    string isLoggedInDb;
    @if(Session["isLoggedInDb"] != null)
    {
        if(Session["isLoggedInDb"].ToString() == "1") 
        {
            <text>isLoggedInDb = "1";</text>
        }
        else
        {
            <text>isLoggedInDb = "0";</text>
        }
    }
</script>

至于在服务器上构建JS,我个人无法忍受这个想法(我不喜欢合并任何客户端/服务器/css代码)。 我不能说它的性能,但我可以说你正在为一个噩梦般的维护场景设置自己,跟踪所有JS的来源,更不用说你失去了轻松调试和管理脚本的能力。

毫无疑问,

您应该采取类似于以下内容的方法:

var isLoggedOn = @Model.IsLoggedInDb

IsLoggedInDb should be part of your ViewModel, your View should not be checking the session, this is very brittle, not easily testable, and the controllers purpose is to orchestrate the data for the presentation layer (view)

The code should work as is, however the Razor Parser is fighting the javascript intellisense, so you might want to move all your C# code logic out of the script tags since it doesnt need to be inside, like the following:

@{  
        string isLoggedInDb;
        if(Session["isLoggedInDb"] != null)
        {
            if(Session["isLoggedInDb"].ToString() == "1") 
            {
                isLoggedInDb = "1";
            }
            else
            {
                isLoggedInDb = "0";
            }
        }
    }
 @*....etc*@
<script type="text/javascript">
    var dblogin=@(isLoggedInDb);

..etc..
</script>

最新更新