简体   繁体   English

Angular和ASP.NET MVC

[英]Angular and ASP.NET MVC

I am learning angular, and I am using ASP.NET MVC5. 我正在学习有角度的东西,并且正在使用ASP.NET MVC5。 I am unable to return data from mvc controller via angular. 我无法通过angular从mvc控制器返回数据。

The route should be localhost/Product/Test, but when angular get method is calling it the url is locahost/Product/Product/Test. 路由应为localhost / Product / Test,但是在调用angular get方法时,其URL为locahost / Product / Product / Test。 Any help is appreacited. 没有任何帮助。

Is the approach I have taken correct also? 我采取的方法也正确吗? Because I have seen many tutorials where they show how to return a view only. 因为我看过许多教程,其中仅显示如何返回视图。 But cannot seem to find how to return a view and data. 但是似乎找不到如何返回视图和数据。

Screenshot 截图 屏幕截图

MVC controller MVC控制器

public ActionResult Test()
        {
            List<Product> products = new List<Product>();
            var db = new HotStuffPizzaContext();

            var result = (from p in db.Products
                          select p)
                          .Where(x => x.ProductID != 0)
                          .Select(a => new
                          {
                              ProductID = a.ProductID,
                              Description = a.Description
                          });
            return View("~/Views/Product/_Test.cshtml", result);
}

Angular app 角度应用

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

myApp.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
    when('/Test', {
        url: '/Product',
        templateUrl: '../../Views/Product/_Test.cshtml',
        controller: 'testCtrl'
    }).otherwise({
        redirectTo: '/'
    });

}]);

myApp.controller('testCtrl', ['$scope', '$http',
  function ($scope, $http) {
      $http.get('Product/Test').success(function (data) {
          $scope.products = data;
      });
  }]);

Partial View 部分视图

<html data-ng-app="myApp">
<head>
    <title></title>
    <script src="../../Scripts/angular.min.js"></script>
    <script src="../../Scripts/angular-route.js"></script>
    <script src="../../Scripts/App/app.js"></script>
</head>
<body data-ng-controller="testCtrl">
    <div>
        <table class="table table-striped">

            <tr data-ng-repeat="p in products">
                <th>id</th>
                <th>description</th>
            </tr>
            <tr>
                <td>{{p.productid}}</td>
                <td>{{p.description}}</td>
            </tr>
        </table>
    </div>
</body>
</html>

Index View 索引检视

<h1>INDEX VIEW</h1>
<div data-ng-view=""></div>

<a href="/Product/Test">Test</a>

<script src="../../Scripts/angular.min.js"></script>
<script src="../../Scripts/angular-route.js"></script>
<script src="../../Scripts/App/app.js"></script>

UPDATE UPDATE JSON结果

First replace "Product/Test" with "/Product/Test" notice the "/" at the beginning 首先将“产品/测试”替换为“ /产品/测试”,并注意开头的“ /”

Your action will are not implemnted to return a json data but a View (which will be plain HTML) sent to your Angular App. 您的操作将不会执行以返回json数据,而是会发送到Angular App的View(将为纯HTML)。

You must return a Json data in your Test action. 您必须在Test操作中返回Json数据。 Replace the following line: 替换以下行:

return View("~/Views/Product/_Test.cshtml");

by this line: 通过这一行:

return Json(result.ToList());

You might need to allow GET method with AJAX request then use: 您可能需要允许GET方法与AJAX请求一起使用:

return Json(result.ToList(), JsonRequestBehavior.AllowGet);

Don't forget to add [GET] attribute to your Test action. 不要忘记在测试操作中添加[GET]属性。

You must look at using ASP.Net Web API instead of ASP.Net MVC. 您必须考虑使用ASP.Net Web API而不是ASP.Net MVC。

Update 1: Based on the comment below this answer : 更新1:根据此答案下面的评论:

Replace linq query by renaming your anonymous type correctly like this : 通过正确重命名您的匿名类型来替换linq查询,如下所示:

var result = (from p in db.Products
               select p)
               .Where(x => x.ProductID != 0)
               .Select(a => new
                {
                    productid = a.ProductID,
                    description = a.Description
                });

Notice that there is no upper case into anonymous type properties. 请注意,匿名类型属性中没有大写字母。 You must use it like this because your AngularJS App need it: 您必须像这样使用它,因为您的AngularJS应用需要它:

<tr>
     <td>{{p.productid}}</td>
     <td>{{p.description}}</td>
</tr>

Update 2: You need to have two actions 更新2:您需要执行两个操作

  • One that return your view Test 一种返回您的视图测试
  • another one to get your data TestData 另一个获取您的数据TestData

Your Test will look like this: 您的Test将如下所示:

public ActionResult Test()
{
     return View("~/Views/Product/_Test.cshtml");
}

Your TestData liek this: 您的TestData喜欢:

public ActionResult TestData()
{
        List<Product> products = new List<Product>();
        var db = new HotStuffPizzaContext();

        var result = (from p in db.Products
                      select p)
                      .Where(x => x.ProductID != 0)
                      .Select(a => new
                      {
                          productid= a.ProductID,
                          description = a.Description
                      });
        return Json(result.ToList(), JsonRequestBehavior.AllowGet);
}

Finally replace the url of $http.get('Product/Test') with $http.get('/Product/TestData') . 最后,将$http.get('Product/Test')的网址替换为$http.get('/Product/TestData')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM