Javascript-форум (https://javascript.ru/forum/)
-   Angular.js (https://javascript.ru/forum/angular/)
-   -   Вывод данных модели WebApi с помощью AngularJS (https://javascript.ru/forum/angular/59899-vyvod-dannykh-modeli-webapi-s-pomoshhyu-angularjs.html)

fadeinmad 02.12.2015 12:33

Вывод данных модели WebApi с помощью AngularJS
 
Только начал изучать AngularJS и WebApi, не до конца понимаю механизм отображения данных. Работаю на VS 2015.

Есть модель:
Код:

public class Person
{
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public int Growth { get; set; }
}

Есть контроллер:
Код:

public class PersonController : ApiController
{
        Person[] persons = new Person[]
        {
          new Person {Id=0, FirstName="Петр", MiddleName="Петрович", LastName="Петров", Growth=24 },
          new Person {Id=1, FirstName="Иван", MiddleName="Иванович", LastName="Иванов", Growth=20 }
        };
 
        public IEnumerable<Person> GetAllPersons()
        {
            return persons;
        }
 
        public IHttpActionResult GetProduct(int id)
        {
            var person = persons.FirstOrDefault((p) => p.Id == id);
            if (person == null) return NotFound();
            return Ok(person);
        }
}

Задача элементарная: вывести ФИО человека с нужным Id. Не понимаю, как вызвать метод контроллера и получить нужное значение.
Index.html:
Код:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>MyTestSite</title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
</head>
<body>
    <div ng-app="TestApp" ng-controller="PersonController">
        <p>ID: <input type="text" ng-model="id"/></p>
        <h1 <!--так понимаю, что вызов метода здесь, но не знаю синтаксиса-->>
              ФИО: {{person.FirstName}} {{person.MiddleName}} {{person.LastName}}</h1>
    </div>
</body>
</html>


krasovsky 08.12.2015 09:12

что за WebApi?
Метод какого контроллера? Этого - PersonController? Думается мне что ты что то путаешь - PersonController у тебя на java?

Noriffik 01.01.2016 21:58

Вместо
Код:

public IHttpActionResult GetProduct(int id)
        {
            var person = persons.FirstOrDefault((p) => p.Id == id);
            if (person == null) return NotFound();
            return Ok(person);
        }

возвращай JSON:
Код:

public JsonResult GetProduct(int id)
{
            var person = persons.FirstOrDefault(p => p.Id == id);
            return Json(person, JsonRequestBehavior.AllowGet);
        }



Часовой пояс GMT +3, время: 21:44.