从 Web API AJAX 结果中将点击绑定添加到 Knockout.js 数组

Adding click binding to a Knockout.js array from Web API AJAX result

我有一个 ASP.NET Web API 方法 returns 产品列表:

public async Task<IEnumerable<Product>> Get()
{
    var products = new IEnumerable<Product>();
    // Data populated here
    return products;
}

此 API 调用由 Knockout.js observableArray 使用:

// Define viewmodel
var myViewModel = {
    products = ko.observableArray([]);
};

// Apply knockout bindings
ko.applyBindings(vm);

// Function that obtains product data
function listProducts(viewmodel) {
    var productsQuery = "api/products/get";

    // Send an AJAX request
    $.getJSON(productsQuery).done(viewmodel.products);
}

我想对这些产品应用点击绑定,在本例中是名为 myClickFunction 的方法。 如果可能,该方法应该是属于我的 Web API 调用返回的对象的函数 :

<ul data-bind="foreach: products">
    <li class="item" data-bind="text: productName, click: myClickFunction">
    </li>
</ul>

我可以向 Web API 结果添加一个函数,然后我可以在 observableArray 中使用它吗?

您应该将 Product 项目视为 DTO,并在前端代码中使用可以传递此类 DTO 的正确视图模型。例如,假设此服务器端 class(因为您还没有显示您的):

public class Product 
{
    public string Name { get; set; }
    public string Description { get; set; }
}

那么你可以有一个像这样的视图模型:

var ProductVm = function (dto) {
    var self = this;
    self.productName = dto.name;
    self.description = dto.description;
    self.myClickFunction = function() {
        // Your function...
    }
}

并按照以下方式传递它们:

function listProducts(viewmodel) {
    var productsQuery = "api/products/get";

    // Send an AJAX request
    $.getJSON(productsQuery).done(function (result) {
        viewmodel.products(result.map(function (dto) { return new ProductVm(dto); }));
    });
}

此外,您可能想尝试使用 mapping plugin or by plainly extending selfdto.

来简化此操作