在 MVC Controller 中,我尝试将数据集合传递回 View 。
private string GetEntityList()
{
var entities = new[]
{
new EntityList{ EntityId = 1, EntityName = "Entity 1"},
new EntityList{ EntityId = 2, EntityName = "Entity 2"},
new EntityList{ EntityId = 3, EntityName = "Entity 3"},
new EntityList{ EntityId = 4, EntityName = "Entity 4"},
new EntityList{ EntityId = 5, EntityName = "Entity 5"}
};
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
return JsonConvert.SerializeObject(entities, Formatting.None, settings);
}
我通过字符串模型将其发送到 View
public ViewResult Index()
{
return View("index","", GetEntityList());
}
在我的 cshtml 文件中,我尝试将模型分配给名为 mvcData 的属性,该属性是我定义的服务的一部分
app.factory("searchAttributes", function() { console.log(@Html.Raw(模型)); 返回 { mvcData:@Html.Raw(Model) }; });此脚本标记驻留在我的 ng-app 内部,因此它在应用程序的范围内,但是当我尝试从 app.controller
引用 if 时,它显示为未定义
app.controller('searchController', ['$scope', 'searchService', 'ngNotifier', '$log', '$timeout', 'searchAttributes', function ($scope, searchService, searchAttributes, ngNotifier, $log, $timeout) {
var vm = this;
//bootstraped data from MVC
$scope.searchAttributes = searchAttributes.mvcData;
}]);
当模型返回到 html 时查看模型,我可以看到它是一个有效的对象。使用 console.log(@Html.Raw(Model)
我看到对象回来了
Object[0] entityId: 1 entityName: "Entity 1"
Object[1] entityId: 2 entityName: "Entity 2"
有什么想法为什么这个对象没有在 Controller 中被拾取吗?即使我将其定义为依赖项,就好像 ng-controller 没有检测到/加载它一样。
最佳答案
您的依赖项出现故障:
app.controller('searchController', ['$scope', 'searchService', 'ngNotifier', '$log', '$timeout', 'searchAttributes', function ($scope, searchService, searchAttributes, ngNotifier, $log, $timeout) {
应该是
app.controller('searchController', ['$scope', 'searchService', 'ngNotifier', '$log', '$timeout', 'searchAttributes', function ($scope, searchService, ngNotifier, $log, $timeout, searchAttributes) {
您当前的代码意味着您的 searchAttributes.mvcData;
实际上引用了未定义的 timeout.mvcData
。
关于javascript - 将数据从 mvc Controller 传递到 Angular Controller 和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125020/