javascript 剃刀块内的asp.net mvc 4 javascript引发错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14427364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:38:10  来源:igfitidea点击:

asp.net mvc 4 javascript inside razor block throws error

c#javascriptjqueryasp.net-mvcasp.net-mvc-4

提问by Hyman

This is my razor code which throws error:

这是我的剃刀代码,它引发错误:

@section script
{
    <script type="text/javascript">
        $(document).ready(function () {
            @if (TempData["Message"] != null)
            {
                showNotification("'" + TempData["Message"].ToString() + "'");
            }
        });
    </script>
}

It says showNotificationdoesn't exist. It thinks this is a C# code where it's a javascript function. Could anybody please let me know how do I fix this error? Thanks!

它说不showNotification存在。它认为这是一个 C# 代码,它是一个 javascript 函数。有人可以让我知道如何解决此错误吗?谢谢!

回答by Martin

Throw a texttag around it, since the compiler thinks your JavaScript is Razor syntax. When you do this, you will need to add a @to the TempData call.

text在它周围抛出一个标签,因为编译器认为你的 JavaScript 是 Razor 语法。执行此操作时,您需要向@TempData 调用添加。

@section script
{
    <script type="text/javascript">
        $(document).ready(function () {
            @if (TempData["Message"] != null)
            {
                <text>showNotification('@TempData["Message"].ToString()');</text>
            }
        });
    </script>
}

回答by Ely

In addition to @Martin's answer, you can also put @: in front of the showNotification call. The @: syntax tells Razor to treat that single line as HTML, where the tells Razor to treat anything within the text tag as HTML (useful for multi line, where @: is good for single line).

除了@Martin 的回答,您还可以将@: 放在showNotification 调用的前面。@: 语法告诉 Razor 将该单行视为 HTML,其中告诉 Razor 将文本标记内的任何内容都视为 HTML(用于多行,其中 @: 适用于单行)。