AngularJS ViewModel Serialization [closed]

2019-09-20 00:20发布

How to serialize the ViewModel ($scope) in AngularJS? I'm planning to store the serialized value to a ASP.NET server-side div to persists across postbacks.

3条回答
萌系小妹纸
2楼-- · 2019-09-20 00:51

I am not sure about how your ASP.Net application is structured, but here are some of my inputs.

If you plan to do postbacks with ASP.Net I would suggest you to rethink you client side framework. AngularJS and many such similar frameworks are not meant for working with postback model. Typically what happens when you use frameworks like AngularJS

  • The server based on the request, sends HTML content (initial view) to client browser
  • The browser renders the view.
  • The client side Javascript frameworks kick in provide the necessary functionality

From this point onwards there is no post back, most of the functionality is achieved using AJAX requests, which does not cause a browser refresh. If a navigate is performed from one page to another the process described above is repeated again.

As you can see postbacks are not natural to this setup, and any effort to bolt these two model together would produce less than optimum results.

查看更多
戒情不戒烟
3楼-- · 2019-09-20 00:55

$scope is an object created by AngularJS to interact with the markup. It can contain methods that can be referenced from html. You can create a simple JavaScript object for storing and transferring data and keep it in your scope.

$scope.model = { name : 'my model' };
查看更多
唯我独甜
4楼-- · 2019-09-20 00:57

Not sure if you should serialize the whole $scope (actually, you shouldn't - it's a complex object. You should only care about persisting your own data).

Use:

angular.toJson($scope.YourData);

obviously, there's a method-companion fromJson: http://docs-angularjs-org-dev.appspot.com/api/angular.fromJson

查看更多
登录 后发表回答