Вызов контроллера MVC из AngularJS с использованием JSON в ASP.Net MVC

Метод JsonResult не вызывается через вызов https://docs.angularjs.org/api/ng/service/$http,

Я работаю над проектом, который использует ASP.NET MVC, AngularJS. Я вызываю контроллер mvc из AngularJS. Я получаю jsonresult, как при вызове контроллера MVC из AngularJS.

это результат

[
  {
    "Branch_ID": 1,
    "Branch_Name": "sdsds",
    "Branch_Address": "sfsdfsdf",
    "Branch_email": "sdfsdfsdf",
    "Branch_Notes": "sfsffsfd",
    "Branch_Manager": null,
    "Branch_Phone": null,
    "Branch_TimeFrom": "/Date(-2208996000000)/",
    "Branch_TimeTo": "/Date(-2208996000000)/",
    "saturday": false,
    "sunday": false,
    "monday": false,
    "tuesday": false,
    "wednesday": false,
    "thursday": false,
    "friday": false,
    "Departments": null
  }
]

контроллер филиалов

public class BranchesController : Controller
   {

    private IRepositoryBase<Branches> BrancheRepository;

    public BranchesController(IRepositoryBase<Branches> brancheRepository)
    {
        this.BrancheRepository = brancheRepository;
    }
    // GET: Branches
    public JsonResult Index()
    {

        var branches =   BrancheRepository.GetAll();

        //if (!String.IsNullOrEmpty(searchString))
        //{
        //    branches = branches.Where(s => s.Branch_Name.ToUpper().Contains(searchString.ToUpper()));
        //}

        return Json(branches, JsonRequestBehavior.AllowGet);
    } 
}

Index.cshtml

<div class="container" ng-controller="branch-controller">
<div class="panel panel-info">
    <div class="panel-heading">
        Branch Details - Grid CRUD operations
    </div>
    <table class="table table-bordered">
        <thead style="background-color:lightblue;">
            <tr>
                <th> Branch Address</th>
                <th> Branch Email</th>
                <th>Branch Name</th>
                <th>Branch Notes</th>
                <th> Actions</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="branche in Branches">
                  <td>{{branche.Branch_ID}}</td>
                <td>{{branche.Branch_Address}}</td>
                <td>{{branche.Branch_email}}</td>
                <td>{{branche.Branch_Name}}</td>
                <td>{{branche.Branch_Notes}}</td>

                <td style="width:200px;">
                    <a href="#" class="btn btn-info">Update</a>
                    <a href="#" class="btn btn-danger">Delete</a>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Module.js

 var myapp;
 (function () {

   myapp = angular.module('my-branches', []);
  })();

Контроллер.js

myapp.controller('branch-controller', function ($scope, branchService) {

//Loads all branch records when page loads
loadBranches();

function loadBranches() {
    var BrancheRecords = branchService.getAllBranches();

    BrancheRecords.then(function (data) {
        //success

        $scope.Branches = data;
    },
    function (error) {
        console.log(error);
        alert("Error occured while fetching branche list...");
    });
    }
  });

Service.js

myapp.service('branchService', function ($http) {

    this.getAllBranches = function () {

        return $http.get("/Branches/Index").then(function (response) {

            return response.data;
        });
    };
});   

person hashim    schedule 15.12.2019    source источник
comment
В чем проблема? Вы не можете нажать действие или получаете ответ, но не можете его отобразить?   -  person Alexander    schedule 15.12.2019
comment
@ Александр, я получаю ответ, но не могу его отобразить, он отображается так [{"Branch_ID":1,"Branch_Name":"sdsds","Branch_Address":"sfsdfsdf","Branch_email":"sdfsdfsdf","Branch_Notes":"sfsffsfd","Branch_Manager":null,"Branch_Phone":null,"Branch_TimeFrom":"/Date(-2208996000000)/","Branch_TimeTo":"/Date(-2208996000000)/","saturday":false,"sunday":false,"monday":false,"tuesday":false,"wednesday":false,"thursday":false,"friday":false,"Departments":null}]   -  person hashim    schedule 15.12.2019


Ответы (2)


Прежде всего, вам нужно изменить свой код, как показано в ответе @georgeawg, а затем ваша оставшаяся проблема заключается в том, что вы использование недопустимых имен свойств. Результат должен выглядеть так

<td>{{branche.Branch_Address}}</td>
<td>{{branche.Branch_email}}</td>
<td>{{branche.Branch_Name}}</td>
<td>{{branche.Branch_Notes}}</td>
person Alexander    schedule 15.12.2019
comment
Все еще есть та же проблема после изменения кода с именами свойств - person hashim; 16.12.2019
comment
у меня та же проблема, подскажите пожалуйста - person hashim; 17.12.2019
comment
@hashim Вы пытались отладить свой код js? Добавьте ключевое слово debugger перед этой строкой return response.data; и проверьте, какие данные содержит response - person Alexander; 17.12.2019
comment
VM246:1 Uncaught ReferenceError: response is not defined у меня такая ошибка - person hashim; 17.12.2019
comment
@hashim Пожалуйста, обновите ваши вопросы с вашим текущим кодом, я постараюсь выяснить проблему. - person Alexander; 17.12.2019
comment
@hashim Попробуйте добавить этот код в начало branch-controller и удалите loadBranches() вызов сейчас $scope.Branches = [{"Branch_ID": 1}] - person Alexander; 17.12.2019
comment
Давайте продолжим обсуждение в чате. - person Alexander; 17.12.2019

Измените вызов службы на:

var BrancheRecords = branchService.getAllBranches();

BrancheRecords.then(function (data) {
    //success
    $scope.Branches = data;
},
  function (error) {
    console.log(error);
    alert("Error occured while fetching branche list...");
});

Измените услугу на:

myapp.service('branchService', function ($http) {

    this.getAllBranches = function () {

        return $http.get("Branches/Index").then(function(response) {
            return response.data;
        });
    };
});

Данные присваиваются свойству data объекта ответа.

Для получения дополнительной информации см.

person georgeawg    schedule 15.12.2019
comment
Все еще есть проблема после изменения моего кода на ваш код - person hashim; 15.12.2019
comment
у меня та же проблема, подскажите пожалуйста - person hashim; 17.12.2019
comment
я не исправил эту ошибку, пожалуйста, посоветуйте - person hashim; 22.12.2019