Passing information from Razor client (cshtml) to AngularJS

11,636

Solution 1

You could embed the following in your razor page:

 <script>
  app.value('myValue', @Html.Raw(Json.Encode(Model)))
 <script>

Where Model is a .NET object you want to render.

Then inject it into your controller:

 app.controller('ctrl', function($scope, myValue) 
 {
      //use myValue
 });

Solution 2

You can pass data in json format to you view and after bootstrap your data using factory ie:

testModule.factory('UserService', function () {

      var _userInfo= @Html.Raw(ViewBag.UserDataInJsonFormat); //<- your data is going here

      return {
      userInfo : _userInfo

      }

}

Share:
11,636
Admin
Author by

Admin

Updated on June 12, 2022

Comments

  • Admin
    Admin almost 2 years

    I have the following razor file:

    @{
        ViewBag.Title = "Blah";
        Layout = "~/Views/Shared/_Layout.cshtml";
        ViewBag.InitModule = "myFooModule";
    }
    
    @section Scripts{
        <script src="~/Scripts/angular-route.js"></script>
        <script src="~/Scripts/angular-route.min.js"></script>
        <script src="~/js/recipes.js"></script>
    }
    <div data-ng-view
    

    Here is my angularjs code:

    var testModule = angular.module("myFooModule", ['ngRoute']);
    
    appetizerModule.config(["$routeProvider", function ($routeProvider) {
        $routeProvider.when("/", {
            controller: "myController",
            templateUrl: "/Templates/test.html"
        });
        $routeProvider.otherwise({ redirectTo: "/" });
    }]);
    

    I would like to pass a variable with data like "myuserinfofromPage" from my razor page to my angularJs so that I can use that data ("myuserinfofromPage") to perform certain set of operations. I am struggling to get a clean way to pass data as I am new to AngularJS. What's the best way to pass simple data from Razor(cshtml) to my Angular code?

  • Admin
    Admin almost 10 years
    Thanks pixelbits and sylwester for your responses. I have used angular directives to pass the element data and stored it in $scope variable in my angular controllers. Reference: fdietz.github.io/recipes-with-angular-js/directives/…
  • Tabetha Moe
    Tabetha Moe almost 9 years
    This worked perfectly. Thank you! Just what I needed!
  • Winnemucca
    Winnemucca over 7 years
    Does it matter if it is _Layout or View?
  • Winnemucca
    Winnemucca over 7 years
    @sylwester I am getting Unexpected token @ in JSON at position 0. Is there anything additional needed?
  • sylwester
    sylwester over 7 years
    @stevek it looks like you have got not valid json