Chet_Steadman Chet_Steadman - 1 year ago 72
Javascript Question

Storing a MVC Model Property to a JavaScript var object syntax error

for some reason I am getting a syntax error when trying to use Razor syntax to store a model object into a JavaScript var. After researching google it seems that I should be able to do something like this. I am using a script tag in my cshtml to do this (I know this is bad practice but I came in late in this project so I'm doing this for uniformity sake) so here is the code.


var isAvailable = @Model.IsAvailable; // This gives me a syntax error

I have a Model class with the Boolean property named IsAvailable and I'm trying to store it in the var isAvailable but Visual Studio doesn't like it. Any idea why?

Answer Source

By default MVC calls ToString(), which Booleans converted to string produce upper-cased values (ie. True) where JS boolean syntax requires lower-cased (ie. true). Try this:

var isAvailable = @(Model.IsAvailable.ToString().ToLower());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download