javascriptjqueryasp.net-mvcasp.net-4.5

Cannot acces object from javascript


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


Solution

  • 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
        }
      }
    };