Passing variables from C# MVC Controller to AngularJS using Razor

I wanted to pass some data from my MVC but didn’t want to go the hassle of creating a seperate WebAPI call and Angular service, so I used the Angular module’s value method. Then I could inject those variables individually into any controller or services that I wanted to.

HomeController.cs

1
2
3
4
5
6
7
8
public ActionResult Index()
{
  return View(new MyModel {
    Id = Guid.NewGuid(),
    Name = "My Name",
    Value = 42
  });
}

Index.cshtml

1
2
3
4
5
6
7
8
9
10
11
@section scripts {
 <script src="~/Scripts/angular.js"></script>
 <script src="~/App/app.js"></script>
 <script>
 angular.module('myApp').value({
 id: '@Model.Id',
 name: '@Model.Name',
 value: @Model.Value,
 });
 </script>
}

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function () {
    angular.module('myApp', []);
 
    angular.module('myApp').controller('myController', myController);
    myController.$inject = ['id', 'name', 'value'];
 
    function myController(id, name, value) {
 
        var vm = this;
 
        vm.id = id;
        vm.name = name;
        vm.value = value;;
    }
})();

It is also possible to inject the data as one object by doing the following:
Index.cshtml

1
2
3
4
5
6
7
8
9
10
11
@section scripts {
  <script src="~/Scripts/angular.js"></script>
  <script src="~/App/app.js"></script>
  <script>
  angular.module('myApp').value('mydata', {
    id: '@Model.Id',
    name: '@Model.Name',
    value: @Model.Value,
   });
 </script>
}

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function () {
    angular.module('myApp', []);
 
    angular.module('myApp').controller('myController', myController);
    myController.$inject = ['mydata'];
 
    function myController(mydata) {
 
        var vm = this;
 
        vm.id = mydata.id;
        vm.name = mydata.name;
        vm.value = mydata.value;;
    }
})();