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

1
  • 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 <script src=myconstants.js is not working. Add an alert as the first line in the include script to ensure it's working. Commented Feb 8, 2021 at 15:07

1 Answer 1

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
    }
  }
};
Sign up to request clarification or add additional context in comments.

3 Comments

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
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.
Finally I have solved, change was not being applied correctly. After clearing chrome cache and history it works. Thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.