[英]Using conditional compile constants to control JavaScript emitted by an MVC3 view
I have gleaned that it is possible to use conditional compiler directives and constants in Razor markup. 我已经收集到可以在Razor标记中使用条件编译器指令和常量。 I would like to know if there is a way to conditionally emit JavaScript text using these directives, as I seek to to below:
我想知道是否有办法使用这些指令有条件地发出JavaScript文本,正如我所寻求的那样:
@section BodyPanelScript
{
<script type="text/javascript">
$(function () {
$(":password").val(null);
// Back up current names of package radio buttons, then make all their names the same for grouping.
$("#package-selector :radio[name$='.IsSelected']").each(function () {
$(this).attr("oldname", $(this).attr("name"));
});
$("#package-selector :radio[name$='.IsSelected']").attr("name", "Package.IsSelected");
// Hook the 'submit' click to restore original radio button names.
$("form#register :submit").click(function () {
$(":radio[name='Package.IsSelected']").each(function () {
$(this).attr("name", $(this).attr("oldname"));
});
});
});
</script>
@{
#if AUTO_FILL_REG
<text>
<script type="text/javascript">
$(function () {
$(":password").val("123456");
});
</script>
</text>
#endif
}
}
The constant AUTO_FILL_REG
is defined in my Debug configuration, and tells the controller to populate the registration model with default values, so I don't have to always complete the form to test the process. 常量
AUTO_FILL_REG
在我的Debug配置中定义,并告诉控制器使用默认值填充注册模型,因此我不必总是完成表单来测试该过程。 Existing values in the model are ignored on the password field, so I resort to some JavaScript to populate this field. 密码字段中忽略模型中的现有值,因此我使用一些JavaScript来填充此字段。 I would like to have this JavaScript conditionally emitted, but several attempts like the code above either result in the
#if...#endif
text being literally rendered, and the password populated, or nothing being rendered, regardless of build configuration. 我希望有条件地发出这个JavaScript,但是像上面代码这样的几次尝试都会导致
#if...#endif
文本被逐字渲染,并且无论构建配置如何,都会填充密码或不渲染任何内容。
This is not a particularly elegant solution, but it is simple. 这不是一个特别优雅的解决方案,但它很简单。 You can make a simple class like this
你可以做一个像这样的简单课程
public static ConditionalValue {
public static bool AUTO_FILL_REG {
get {
#if DEBUG
return true;
#else
return false;
#endif
}
}
}
and then just reference this in your aspx. 然后在你的aspx中引用它。 This is just one example of where you could place this property.
这只是您可以放置此属性的一个示例。 You could do it as constants as well, but you get the idea.
你也可以把它作为常数来做,但你明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.