【发布时间】: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