1

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

Ivar
  • 6,138
  • 12
  • 49
  • 61
Willy
  • 9,848
  • 22
  • 141
  • 284
  • `jQuery.Deferred exception` would 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 your `var` has been setup correct (eg your ` – freedomn-m Feb 08 '21 at 15:07

1 Answers1

2

MyConstants is a function which returns an object, so you need to invoke it:

var myEnum = MyConstants().DataObject1.MyEnum1.Item1; 

If you'd prefer to keep your current syntax to retrieve the value, then you need to convert MyConstants to an object:

var MyConstants = {
  DataObject1: {
    MyEnum1: {
      Item0: 0,
      Item1: 1,
      Item3: 2
    }
  },
  DataObject2: {
    MyEnum2: {
      Item0: 0,
      Item1: 1,
      Item3: 2
    }
  }
};
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • I have changed to MyConstants() instead of using MyConstants but it does not work.From devtools in chrome I have checked this line and chrome gets MyConstants.DataObject1.MyEnum1.Item1 even if I type in javascript MyConstants().DataObject1.MyEnum1.Item1 – Willy Feb 08 '21 at 14:49
  • In which case we need more information about the error, and how and when you include the script in the page, as the example above works fine. – Rory McCrossan Feb 08 '21 at 14:52
  • 1
    Finally I have solved, change was not being applied correctly. After clearing chrome cache and history it works. Thx. – Willy Feb 08 '21 at 15:08