开发者

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. I would like to know if there is a way to conditionally emit JavaScript text using these directives, as I seek to to below:

@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.IsSelec开发者_如何学运维ted");

            // 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. Existing values in the model are ignored on the password field, so I resort to some JavaScript to populate this field. 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.


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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜