Question

I'm curious as to how model binding is handled when not using razor but some client side framework (knockout, angular, etc.).

For instance the model binder requires something like [0].Collection[0].Property for a name, which razor will generate automatically for a complex object with a nested collection.

How does one leverage a client side technology that allows one to dynamically update a model while still satisfying these requirements? Is there a simpler way or must one manually create/recreate indexes, etc.

Était-ce utile?

La solution

When dealing with client side frameworks to represent your models you no longer have to worry about manually creating indexes as your collections are represented as javascript arrays.

An example using knockoutjs:

Knockout View Model

var OrdersModel = function (Order) {
    var self = this;

    self.OrderNumber = ko.observable(Order ? Order.OrderNumber : 0);
}

var ViewModel = function () {
    var self = this;

    self.Orders = ko.observableArray([]);

    self.AddOrder = function (Order) {
        self.Orders.push(Order);
    }

    self.RemoveOrder = function (Order) {
        self.Orders.remove(Order);
    }

    self.LoadOrders = function () {
        // AJAX to load orders from DB
    }

    self.LoadOrders();
}

HTML

<section id="orders" data-bind="foreach: Orders">
    <input type="text" data-bind="attr: {
                                      name: 'Orders[' + $index() + '].OrderNumber
                                  }" />
</section>

C# Model

public class OrderModel {
    public int OrderNumber { get; set; }
}

C# ViewModel

public class OrdersViewModel {
    public List<OrderModel> Orders { get; set; }

    public OrdersViewModel() {
        this.Orders = new List<OrderModel>();
    }
}

This is a very simple example, but knockout js will build inputs like:

<input type="text" name="Orders[0].OrderNumber" />
<input type="text" name="Orders[1].OrderNumber" />

So when you POST these to a controller, the model binder will work appropriately and build a list of Orders with the appropriate OrderNumber.

Now that our orders are stored in an observableArray, if we call AddOrder or RemoveOrder, all indexes will be updated automagically by knockout js, thus preserving indexing for our model binder with no additional action on our part to make it work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top