【问题标题】:Syntax Error when writing @Html.Raw(Html.Debug) in ASP.NET MVC在 ASP.NET MVC 中编写 @Html.Raw(Html.Debug) 时出现语法错误
【发布时间】:2013-11-26 15:24:18
【问题描述】:

我正在尝试将 C# 代码与 MVC 中的 javascript 结合起来,以便仅在我在调试模式下使用页面时启用“调试”。

这里出现错误:

<script type="text/javascript">
    $(document).ready(function () {
        Control.init(
            "@(ViewBag.Control)", 
            @Html.Raw(Html.IsDebug() ? "true" : "false")
            );
    });
</script>

在行中:@Html.Raw(...) 我得到“语法错误”

完整代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title></title>

    @Styles.Render("~/Content/css/normalize")
    @Styles.Render("~/Content/css/bootstrap")

    @Scripts.Render("~/bundles/modernizr")

    @RenderSection("head", false)

</head>
<body>

    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/js/control")

    <script type="text/javascript">
        $(document).ready(function () {
            Control.init(
                "@(ViewBag.Control)", 
                @Html.Raw(Html.IsDebug() ? "true" : "false")
                );
        });
    </script>


    @RenderSection("scripts", false)

</body>
</html>

是调试方法:

using System.Web.Mvc;

namespace System.Web.Mvc
{
    public static class GUIHelper
    {
        public static bool IsDebug(this HtmlHelper htmlHelper)
        {
#if DEBUG
            return true;
#else
            return false;
#endif
        }
    }
}

当我这样做时:

"@(Html.IsDebug() ? "true" : "false")"

代替:

@(Html.IsDebug() ? "true" : "false") 

有效,但是...:

<script type="text/javascript">
    $(document).ready(function () {
        Control.init(
            "Control1", 
            "true" // instead of true
            );
    });
</script>

* 更新:2013-11-27 *

解决方案 1:

<script type="text/javascript">
    $(document).ready(function () {
        Control.init(
            "@(ViewBag.Control)", 
            "@(Html.IsDebug() ? "true" : "false")" == "true"
            );
    });
</script>

解决方案 1:

<script type="text/javascript">


    $(document).ready(function () {
        @Html.Raw("Control.init("+ViewBag.Control+","+(Html.IsDebug() ? "true" : "false")+")")
    });
</script>

【问题讨论】:

  • 你是如何实现IsDebug方法的?
  • 已更新,请查看

标签: c# javascript asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

试试这个?

@{Html.Raw(Html.IsDebug() ? "true" : "false")}

【讨论】:

  • 我仍然遇到“语法错误”...我也尝试过 @(Html.IsDebug() ? "true" : "false") 但不起作用
  • 不工作......我不知道为什么,但如果我这样做:与“”一样工作......就像:“@ {Html.Raw(Html.IsDebug()? "true" : "false");}"... 但我不想要 '"false"' 或 '"true"',我想要 'false' 或 'true'
  • 你总是可以将整个 Control.init statemtn 放入 Html.Raw 并使用字符串 concat 来构建整个语句,这样就可以了
【解决方案2】:

这为我提供了所需的输出:

@(Html.Raw(Html.IsDebug() ? "true" : "false"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2019-02-18
    相关资源
    最近更新 更多