【发布时间】:2015-09-05 20:33:23
【问题描述】:
我一直在努力使用 AngularJs 在 ASP.NET 网络表单中进行数据绑定。
我有以下角度:
(function () {
var app = angular.module("registrationModule", []);
app.factory("exampleService", exampleService);
function exampleService($http) {
function getData(id) {
return $http.post("LegacyPage.aspx/GetData", { id: id })
.then(function (response) {
return response.data; //data comes back as json
//Also tried response.data.d
});
};
return {
getData: getData
};
};
app.controller("MainCtrl", ["$scope", "exampleService", MainCtrl]);
function MainCtrl($scope, exampleService) {
$scope.generateText = "Generate";
$scope.loading = false;
function onComplete(data) {
Unload(data);
}
function err(reason) {
Unload("Ajax has failed.");
}
$scope.GetData = function (id) {
Load();
exampleService.getData(id).then(onComplete, err);
}
function Unload(result) {
$scope.loading = false;
$scope.generating = false;
$scope.generateText = "Generate";
$scope.theData = result; //does not work
//I have tried (with no success):
//$scope.$apply(function () {
//$scope.theData = result;
//});
//$scope.theData = JSON.parse(result);
//$scope.theData = angular.fromJson(result);
}
function Load() {
$scope.loading = true;
$scope.generating = true;
$scope.generateText = "Generating...";
}
};
}());
我的 HTML:
<div ng-app="registrationModule">
<div ng-controller="MainCtrl">
<input style="display: block; margin: 0 auto;" type="text" class="form-control" placeholder="ID" ng-model="id" />
<input ng-click="GetData(id)" type="button" class="btn btn-primary btn-lg" value="{{generateText}}" ng-disabled="generating" />
<div class="row">
<div class="span10">
<table class="table table-responsive table-hover table-condensed">
<tr>
<th>ID</th>
<th>Activity Code</th>
<th>Duration</th>
<th>Date Created</th>
</tr>
<tr ng-repeat="element in theData">
<td>{{element.ID}}</td>
<td>{{element.ActivityCode}}</td>
<td>{{element.Duration}}</td>
<td>{{element.DateCreated}}</td>
</tr>
</table>
<br />
</div>
</div>
</div>
</div>
代码背后/后端 c#:
[WebMethod]
public static string GetData(int id)
{
var dt = GetData(id);
if (dt == null) return "";
var json = dt.Serialize() ?? "";
return json;
}
public static string Serialize(this DataTable dt)
{
if (dt == null)
{
throw new NullReferenceException("dt parameter cannot be null");
}
try
{
var serializer = new JavaScriptSerializer();
var rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
catch
{
return null;
}
}
本质上,数据以 JSON 形式返回,但未成功绑定。我将 JSON 恢复为有角度的,但我无法处理它。我想我只是错过了一些非常简单的东西,但还没有找到解决方案
【问题讨论】:
标签: javascript c# asp.net json angularjs