Проблемы с MVC 4 и нокаутом

0

Я очень новичок в MVC, и я хочу реализовать простое веб-приложение с Knockout, и я застрял.

Ни одна из моих привязок данных не работает. Когда страница загружается, я вижу, что в Fiddler есть Get на сервер, и он возвращает действительный Json со всеми Destinos, но он не отображается в представлении.

Посмотреть:

    <div id="right_col" class="right">

        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Direccion</th>
                    <th>lat</th>
                    <th>lng</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: Destinos">
                <tr>
                    <td data-bind="text: Id"></td>
                    <td data-bind="text: Direccion"></td>
                    <td data-bind="text: lat"></td>
                    <td data-bind="text: lng"></td>
                </tr>
            </tbody>
        </table>
        <br />
        <button data-bind="click: $root.GetDestinos">Get</button>

    </div>

Javascript [Нокаут]:

function DestinoVM () { //ViewModel
    //Make the self as 'this' reference
    var self = this;
    //Declare observable which will be bind with UI 
    self.Id = ko.observable("");
    self.Direccion = ko.observable("");
    self.lat = ko.observable("");
    self.lng = ko.observable("");

        //The Object which stored data entered in the observables
        var DestinoData = {
            Id: self.Id,
            Direccion: self.Direccion,
            lat: self.lat,
            lng: self.lng
        };

        //Declare an ObservableArray for Storing the JSON Response
        self.Destinos = ko.observableArray([]);

        GetDestinos(); //Call the Function which gets all records using ajax call



        //Function to Read All Destinos
        function GetDestinos() {
            //Ajax Call Get All Employee Records
            $.ajax({
                type: "GET",
                url: "/api/destino",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    self.Destinos(data); //Put the response in ObservableArray
                },
                error: function (error) {
                    alert(error.status + "<--and--> " + error.statusText);
                }
            });
            //Ends Here
        }

    };
    ko.applyBindings(new DestinoVM());

Модель:

public class Destino
    {
        [Key,DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string lat { get; set; }
        public string lng { get; set; }
        public string Direccion { get; set; }
    }

С уважением.

Теги:
asp.net-mvc
knockout.js

1 ответ

2
Лучший ответ

Пожалуйста, взгляните на эту реализацию:

function DestinoPage() {
    this.Destinos = ko.observableArray([]);
}

function Destino(data) {
    this.Id = ko.observable(data.Id);
    this.Direccion = ko.observable(data.Direction);
    this.lat = ko.observable(data.lat);
    this.lng = ko.observable(data.lng);
};

$(function () {

    var page = new DestinoPage();

    ko.applyBindings(page);

    $.ajax({
        type: "GET",
        url: "/api/destino",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {

            $(data).each(function () {
                page.Destinos.push(new Destino(this));
            });

        },
        error: function (error) {
            alert(error.status + "<--and--> " + error.statusText);
        }
    });

});

Я немного изменил структуру. Главное правило - держать все просто.

  • 0
    Спасибо. Я переписал свой код, используя ваш в качестве ссылки, и это сработало. С уважением.
  • 0
    @wOvalle рад помочь вам

Ещё вопросы

Сообщество Overcoder
Наверх
Меню