I am working on a MVC application, and would like some code in JavaScript to run only if I am in debug mode. I do not want that code to run when I release the code.
In other words, is there anything similar to the following code in C#, for javascript / jQuery?
#if (DEBUG)
// debugging code block here
#else
// release code block here
#endif
I am working on a MVC application, and would like some code in JavaScript to run only if I am in debug mode. I do not want that code to run when I release the code.
In other words, is there anything similar to the following code in C#, for javascript / jQuery?
#if (DEBUG)
// debugging code block here
#else
// release code block here
#endif
Share
Improve this question
edited Jul 29, 2013 at 23:17
tereško
58.5k25 gold badges100 silver badges150 bronze badges
asked Jul 23, 2013 at 22:43
TK1TK1
3962 gold badges7 silver badges20 bronze badges
3
-
following code in C# for javascript
some code in javascript
Which language?! Above snippet looks fine... – Dave Chen Commented Jul 23, 2013 at 22:45 - Just create a global called DEBUG, but you should really remove all debugging code on a production site, so I don't see the point ? – adeneo Commented Jul 23, 2013 at 22:45
- the way my application is designed, I use a different set of variables when debugging than in production. so I do need this kind of a functionality for my application.. – TK1 Commented Jul 23, 2013 at 22:49
3 Answers
Reset to default 5I'd suggest using the construct in your question and setting something in your viewmodel to include/exclude the javascript.
public ActionResult XXX()
{
var vm=new MyViewModel(); //or just use ViewBag/ViewData
#if (DEBUG)
vm.RunJS=true;
#else
vm.RunJS=false;
#endif
return View(vm);
}
then in your view
@if(Model.RunJS)
{
<script ...></script>
}
or use a similar construct to pass the DEBUG status through to your javascript.
<script type="text/javascript">
startMyJavascript(@Model.IsDebug?"true":"false");
</script>
(not so sure about Razor syntax, but I think the above is good)
Sure. Here is the JavaScript version.
var DEBUG = true;
if(DEBUG) {
// debug code
} else {
// production code
}
You can always use the ViewBag along with @Html.Raw(). I do this occasionally and it works well.
Controller:
#if DEBUG
ViewBag.JavaScript = "String representation of JS code";
#endif
return View();
View:
@Html.Raw(ViewBag.JavaScript)
I would also remend using an include such as
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
rather than the raw JavaScript to avoid having to put all of that mess in your controller.