我开始学习一些AngularJS
并试图确定其与ASP.NET
MVC
一起工作时的实用性。
我们说我有一个视图,可以显示表格中存储库中的啤酒。我可以用两种方式输出信息。
1.使用MVC的Razor引擎</ strong>
此处,包含啤酒的模型在服务器上处理并呈现html页面。
<h3>Rendered using Razor!</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Colour</th>
<th>Tasted?</th>
</tr>
</thead>
<tbody>
@foreach (var beer in Model)
{
<tr>
<td>@beer.Name</td>
<td>@beer.Colour</td>
<td>@beer.Tried</td>
</tr>
}
</tbody>
</table>
2.使用Angular repeat
此处,HTML会立即返回,而angular会对控制器执行AJAX
调用以检索其模型。拥有该数据后,将其输出到表格中。
<h3>Rendered using Angular!</h3>
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Name</th>
<th>Colour</th>
<th>Tasted?</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="beer in model">
<td>{{ beer.Name }}</td>
<td>{{ beer.Colour }}</td>
<td>{{ beer.Tried }}</td>
</tr>
</tbody>
</table>
控制器
angular.module('BeerController', [])
.controller('BeerCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.model = {};
$http.get('/Beer/GetBeers').success(function (data) {
$scope.model = data;
});
}]);
我的问题
有没有办法使用Razor引擎进行数据的初始加载,Angular用于其他所有内容(分页调用,搜索等)?换句话说,如何将现有的html绑定到AngularJS中的控制器模型?
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Colour</th>
<th>Tasted?</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fosters</td>
<td>Gold</td>
<td>True</td>
</tr>
<tr>
<td>Becks</td>
<td>Amber</td>
<td>False</td>
</tr>
<tr>
<td>Cobra</td>
<td>Gold</td>
<td>True</td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
在MVC控制器中
public ActionResult Index()
{
var model =.....
//optional
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
ViewBag.data = JsonConvert.SerializeObject(model, Formatting.Indented, jsonSerializerSettings);
return View()
}
在您的视图中查看Index.cshtml
...
@section Scripts {
//make sure that all anular scripts are loaded before that
<script>
angular.module('BeerController').service('dataService', function () {
var data= @Html.Raw(ViewBag.data);
return {
data:data
}
});
...
</script>
}
Angular Part:
angular.module('BeerController', [])
.controller('BeerCtrl', ['$scope', '$http','dataService', function ($scope, $http,dataService) {
// now you can get data from your dataService without extra trip to your server
$scope.model = dataService.data
....
}]);