Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign ASP.NET MVC model to AngularJS scope

Below the code of my view (the javascript code is in the view, just temp just for testing).

I'd like assign the ASP.NET MVC model (@Model) to the AngularJS scope ($scope.person)

How can I do this ?

Thanks,

The view

@model MyApp.Person

<script>
var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = ?????
}]);
</script>

Update 1 : I tried this code, in the JS file :

var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = @Html.Raw(window.person);
}]);

In the view file :

<script>
    @{
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    }
    window.person = serializer.Serialize(Model);
</script>

I get 2 errors :

ReferenceError: serializer is not defined (on windows)
window.person = serializer.Serialize(Model);

SyntaxError: illegal character (it's the @)
$scope.person = @Html.Raw(window.person);
like image 459
Kris-I Avatar asked Sep 25 '14 06:09

Kris-I


2 Answers

<script>
    @{
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var json = serializer.Serialize(Model);
    }
    var myApp = angular.module('myApp', []);

    myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
        $scope.person = @Html.Raw(json);
    }]);
</script>
like image 123
Jason Li Avatar answered Sep 28 '22 06:09

Jason Li


I am not sure if this will work with Angular.

You can use Json.Encode Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable.

In Your angular code use,

$scope.person = window.person

However, Best solution will be to create a service and fetch the person data using the service.

Complete Code

@model MyApp.Person

<script>
window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable.
var myApp = angular.module('myApp', []);

myApp.controller('personController', ['$scope', '$http', function ($scope, $http) {
    $scope.person = window.person
}]);
</script>
like image 32
Satpal Avatar answered Sep 28 '22 06:09

Satpal