In my ASP.NET MVC application, in ..\Views\Shared_Layout.cshtml I have the following line of code:
> <script type="text/javascript" src="http://mycontrols.com/Scripts/MyConstants.js"></script>
File MyConstants.js contains below:
var MyConstants = function() {
return {
DataObject1: {
MyEnum1: {
Item0: 0,
Item1: 1,
Item3: 2
}
},
DataObject2: {
MyEnum2: {
Item0: 0,
Item1: 1,
Item3: 2
}
}
};
};
Now from my view (Index.cshtml) I am trying to access in javascript to an item from MyEnum1:
var myEnum = MyConstants.DataObject1.MyEnum1.Item1;
but it does not work, below the error en devtools in chrome:
jQuery.Deferred exception: Cannot read property 'MyEnum1'of undefined TypeError: Cannot read property 'MyEnum1' of undefined
jQuery.Deferred exceptionwould occur when your code is inside a jquery callback (eg doc.ready) when the property doesn't exist. If you're using()(or not) correctly according to Rory's answer then it's possible your code is running before yourvarhas been setup correct (eg your<script src=myconstants.jsis not working. Add analertas the first line in the include script to ensure it's working.