在ASP.NET MVC中写入@Html.Raw(Html.Debug)时出现语法错误

Syntax Error when writing @Html.Raw(Html.Debug) in ASP.NET MVC

本文关键字:Debug Html 错误 语法 Raw MVC NET ASP @Html      更新时间:2023-10-13

我正试图将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>

试试这个?

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

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

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