【问题标题】:AngularJS not showing Entity Framework dataAngularJS 不显示实体框架数据
【发布时间】:2015-08-19 21:12:42
【问题描述】:

{{project.ProjectName}} 在我的浏览器中没有显示任何数据。我在数据库中有数据,在我的_Layout 中有所需的脚本文件,在正文中有ng-app="myApp"。调试控制器确实返回 1 行数据。不知道我做错了什么。它应该显示 1 行的 ProjectName。

控制器:

 public ActionResult Index()
        {
            return View();
        }

    public JsonResult GetAllProjects()
    {
        EEDBEntities db = new EEDBEntities();
        var result = db.Projects.ToList();
        return Json(result, JsonRequestBehavior.AllowGet);
    }

App.js:

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

myApp.controller('mainController', function($scope, $http) {
    $http.get('/home/GetAllProjects')
        .success(function(result) {
            $scope.projects = result;
        })
        .error(function(data) {
            console.log(data);
        });
});

Index.cshtml:

<h3>
    All Projects
</h3>
<div ng-controller="mainController">
    <table class="table table-striped">
        <tr ng-repeat="project in projects">
            <td>{{project.ProjectName}}</td>
            <td class="text-right">
                <button class="btn-danger">X</button>
            </td>
        </tr>
    </table>
</div>

【问题讨论】:

  • 您能否尝试将{{projects}} 置于视图中以检查projects 是否已加载。?
  • 所有项目

  • 哎呀,什么都没有显示
  • 调试控制台我确实看到了: 在序列化“System.Data.Entity.DynamicProxies.Project_83750B92BCA5CE51EC420CEFFEAF12AA8B672E61DCC85D715490C55AF863FA22”类型的对象时检测到循环引用。跨度>
  • 我添加了 this.Configuration.ProxyCreationEnabled = false;到我的实体上下文构造函数并且有效。不确定这是否有任何缺点?

标签: angularjs asp.net-mvc entity-framework-6


【解决方案1】:

试着把它放在你的 EF DbContext 构造函数中

base.Configuration.ProxyCreationEnabled = false;

假设你先做 EF 代码。

public YourDbContext()
            : base("name=ConnectionString")
        {
            base.Configuration.ProxyCreationEnabled = false;
        }

【讨论】:

  • 是的,我就是这么做的。我会给你一个功劳。
【解决方案2】:

如果您使用 ViewModel 而不是将实体框架数据发送到您的视图,则可以解决此问题。

就像在您的示例中一样,您似乎只需要 ProjectName 属性,它看起来像这样:

public JsonResult GetAllProjects()
{
    EEDBEntities db = new EEDBEntities();
    var result = db.Projects.Select(p => new {
        p.ProjectName
        //add other properties if you need to
    }).ToList();
    return Json(result, JsonRequestBehavior.AllowGet);
}

给出的示例是使用匿名对象,但您也可以使用真正的 ViewModel,只需将 Select() 更改为以下内容:

    var result = db.Projects.Select(p => new ProjectViewModel {
        ProjectName = p.ProjectName
        //add other properties if you need to
    }).ToList();

【讨论】:

    猜你喜欢
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多