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
3 Answers 3
I'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)
4 Comments
if(1 == 2)alert("hey") else alert("hi") the javascript received by the browser is: alert("hi")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 recommend 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.
following code in C# for javascriptsome code in javascriptWhich language?! Above snippet looks fine...