Server side paging with DataTables.js and MVC

Source code for this article can be found here – https://github.com/RossWhitehead/ServerSidePagingDataTables

When evaluating the usefulness of a javascript grid library the first thing I do is determine whether it is possible to implement server-side paging. This is a must-have feature for most business scenarios, and you will be backing yourself into a corner if you implement a grid that only supports client-side paging.

In a previous post I demonstrated how to implement server side paging with KoGrid. I’m going to repeat this demonstration, but this time for DataTables.NET.

I like KoGrid. It’s based on Knockout, which in my humble opinion is the bees-knees, and my go-to when developing all but the most basic of MVC views.

I also like DataTables.NET.

Both KoGrid and DataTables.NET are widely used and well respected in the community. They meet most demands placed on them, but they differ in terms of their implementation. There’s a good article by Jason Howard here comparing the two. And I agree with most of the statements with the caveat that I am reserving judgement on the assertion that DataTables.NET works with Knockout. I have not yet managed to get the 2 working together when implementing server-side paging. And I will reserve judgment until I have either succeeded or failed miserably.

So onto the implementation of server side paging with DataTables.NET and MVC (without Knockout).

This is what I’m going to build –

BasicDataTable

When initializing the grid, rather than requesting all products from the server, the client is going to request a single page of products. And when the user interacts with the grid – either changing the number of entries to view, selecting a new page, clicking on a column header to sort, clicking on the refresh button, or typing in the search box – the client will update the grid by requesting products one page at a time. In so doing the server will receive a greater number of requests. However, each request will only be for a small page of data, and so should take significantly less resources to meet. Additionally, the client will not be charged with initializing the page with a huge amount of data.

I will be presenting the solution in the following order –

  1. Model
  2. Controller
  3. View
  4. View Model

1. Model

ProductCategory.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ServerSidePagingDataTables.Models
{
    public class ProductCategory
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ProductCategoryId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        // Navigational Properties
        public virtual ICollection<Product> Products { get; set; }
    }
}

Product.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ServerSidePagingDataTables.Models
{
    public class Product
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ProductId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [Required]
        [StringLength(1000)]
        public string Description { get; set; }

        [Required]
        public int ProductCategoryId { get; set; }

        // Navigation properties
        public virtual ProductCategory ProductCategory { get; set; }
    }
}

ServerSidePagingDataTablesDbContext.cs

using System.Data.Entity;

namespace ServerSidePagingDataTables.Models
{
    public class ServerSidePagingDataTablesDbContext : DbContext
    {
        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<ProductCategory> ProductCategories { get; set; }
    }
}

I am using Entity Framework code-first.

I have 2 entities – ProductCategory and Product, with a one-to-many relationship between them. And I have a DbContext called DataTablesDemoDbContext, which is used to map the model to the database.

2. Controller

using DataTables.Mvc;
using System;
using System.Linq;
using System.Linq.Dynamic;
using System.Web.Mvc;
using ServerSidePagingDataTables.Models;

namespace ServerSidePagingDataTables.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult DataTableGet([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
        {
            var db = new ServerSidePagingDataTablesDbContext();

            IQueryable<Product> query = db.Products;

            var totalCount = query.Count();

            // Apply filters
            if (requestModel.Search.Value != String.Empty)
            {
                var value = requestModel.Search.Value.Trim();
                query = query.Where(p => p.Name.Contains(value) || p.Description.Contains(value));
            }

            var filteredCount = query.Count();

            // Sort
            var sortedColumns = requestModel.Columns.GetSortedColumns();
            var orderByString = String.Empty;

            foreach (var column in sortedColumns)
            {
                orderByString += orderByString != String.Empty ? "," : "";
                orderByString += (column.Data == "Category" ? "ProductCategory.Name" : column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
            }

            query = query.OrderBy(orderByString == String.Empty ? "name asc" : orderByString);

            // Paging
            query = query.Skip(requestModel.Start).Take(requestModel.Length);

            var data = query.Select(p => new
            {
                ProductId = p.ProductId,
                Name = p.Name,
                Description = p.Description,
                Category = p.ProductCategory.Name
            }).ToList();

            return Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount), JsonRequestBehavior.AllowGet);
        }
    }
}

I have an MVC controller with 2 actions.

Index serves up a .cshtml page that contains the UI markup (view) and the javascript (view model). I do not pass any data to the view – as the view model will be requesting the data once the page has been loaded.

DataTableGet returns a Json response containing the data required to initialize or update the grid. This action will be called by the view model using Ajax when the grid needs updating with new data.

The first thing of note about the DataTableGet action is that it uses a custom model binder, DataTableBinder, to map the request to the IDataTableRequest requestModel parameter. The DataTableGet action also responds with an instance of DataTablesResponse serialized to a Json string.

The aforementioned interfaces and classes can be downloaded from Nuget.

PM> Install-Package datatables.mvc5

The reason we need a custom model binder is that when the DataTable.NET client code makes Ajax requests for new data, the request details, such as the page required, number of records, sort orders, and search strings, are passed using query string parameters. And the naming convention used by DataTables.NET is not compatible with the default MVC model binders, as you can see from the example URL below.

http://localhost:50055/api/datatableproducts?draw=1&columns[0][data]=productId&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=name&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=description&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&
columns[2][search][regex]=false&columns[3][data]=category&columns[3][name]=&columns[3][searchable]=true&columns[3][orderable]=true&columns[3][search][value]=&columns[3][search][regex]=false&order[0][column]=0&order[0][dir]=asc&start=0&length=10&search[value]=&search[regex]=false&_=1437911688049

The DataTableGet action creates an instance of the database context, and constructs a query to grab a page of products, whilst applying the requested filters and sort orders. I have used System.Linq.Dynamic to simplify the construction of the query. This library is not included in an MVC project by default. It needs to be loaded from NuGet.

PM> Install-Package System.linq.Dynamic

3. View

 <link href="//cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" /> 

I am creating a DataTables.NET grid styled with bootstrap. I therefore need to include the dataTable.bootstrap.css stylesheet in my view.

<style type="text/css">
    .list-panel {
        margin-top: 20px;
    }

        .list-panel .panel-heading {
            overflow: auto;
            padding: 5px 20px;
        }

        .list-panel .panel-title {
            float: left;
            margin-top: 10px;
        }

        .list-panel .panel-body {
            padding: 20px 20px 10px 20px;
        }

        .list-panel .refresh-button {
            float: right;
        }

    .data-table {
        border-collapse: collapse;
        border-spacing: 0;
    }
</style>

And some styling for the panel that grid will sit in.

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h3 class="panel-title list-panel-title">Products</h3>
                <button type="button" class="btn btn-default btn-md refresh-button" id="refresh-button">
                    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Refresh
                </button>
            </div>
            <div class="panel-body">
                <table id="data-table" class="table table-striped table-bordered" style="width:100%"></table>
            </div>
        </div>
    </div>
</div>

The HTML for the grid is a simple <table> element, which I have placed in a bootstrap panel along with a refresh button.

4. View Model

<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.js"></script>

The view model includes the DataTables.NET JQuery library (jquery.dataTables.min.js), and additional includes the DataTables,NET Bootstrap integration library (dataTables.bootstrap.js). This library can be omitted if you do not want to use Bootstrap with you grid.

<script type="text/javascript">
    $(function () {
        var productListVM = {
            dt: null,

            init: function () {
                dt = $('#data-table').DataTable({
                    "serverSide": true,
                    "processing": true,
                    "ajax": "/home/datatableget",
                    "columns": [
                        { "title": "Product Id", "data": "ProductId", "searchable": false },
                        { "title": "Name", "data": "Name" },
                        { "title": "Description", "data": "Description" },
                        { "title": "Category", "data": "Category" }
                    ],
                    "lengthMenu": [[2, 5, 10, 25], [2, 5, 10, 25]]
                });
            },

            refresh: function () {
                dt.ajax.reload();
            }
        }

        $('#refresh-button').on("click", productListVM.refresh);

        /////////////////////////////////////////////////////////////////
        // Let's kick it all off
        productListVM.init();
    })
</script>

I have encapsulated the view model functionality into a javascript object called productListVM.

productListVM has a init function which initializes the grid by calling the DataTables.NET DataTable function. It passes in a number of configuration options to define how the grid will look and behave. “serverSide”: true enables server side processing, “processing”: true tells DataTable.NET to display a “Processing..” message when the grid is being updated, and “ajax”: “/home/datatableget” defines the data-source for the Ajax requests. These 3 options are all that are required to implement server side paging. The grid will respond to all relevant user interaction – sorting, filtering, and paging – by automatically requesting the relevant data from the server and updating the grid. No other view model coding is required, and this is the beauty of server side processing with DataTables.NET. Compare this with KoGrid where it is necessary to write code to define subscriptions to a number of events and to construct the request data.

productListVM also has a refresh function, which forces a reload of the grid. The refresh button is assigned a click event handler which call the this function.

And finally, everything thing is kicked off, with the grid being initialized, by calling productListVM.init().

WCF Crib Sheet – Configuring a Service and Hosting on IIS 5/6

WCF on IIS 5/6

  • IIS manages the lifecycle of the host processes.
  • IIS 5/6 only supports HTTP/HTTPS.

Hosting a WCF service to IIS

  • Create a virtual directory.
  • Create a .SVC file, detailing the service class and assembly, and deploy to the virtual directory.
<!--ProductService.svc-->
<%@ ServiceHost Language="C#" Debug="true" Service="BikeStore.WcfServiceLibrary.ProductService" %>
<%@ Assembly Name="BikeStore.WcfServiceLibrary" %>
  • It is good practice to implement the service in a WCF Service Library, keeping it separate from the service hosting application.

Configuring a WCF service

  • Create a web.config file and deploy to the virtual directory.

Services

  • Add a <service> element for each service, with the name attribute equal to the fully-qualified service class.
  • An optional behaviorConfiguration attribute can be used to assign a set of service behaviors to a service. If this attribute is missing or equal to “” then the service will assume the default set of behaviors
<system.serviceModel>
    <services>
      <service name="BikeStore.WcfServiceLibrary.ProductService">
        ...
      </service>
    </services>
</system.serviceModel>

Endpoints

  • For each service, add one or more <endpoint> elements, detailing addresses and binding protocols available to clients.
  • Each <endpoint> element has an address attribute specifying a URI for contacting the service. This can be an absolute address or one relative to the base address of the service.
  • Each <endpoint> has a binding attribute detailing the type of transport, security, and encoding. IIS 5/6 only supports Http bindings –
    • basicHttpBinding – backwards compatibility for ASMX (SOAP 1.1) clients. Supports HTTP and HTTPS, but does not incorporate WS-* standards.
    • wsHttpBinding – SOAP 1.2. Supports HTTP and HTTPS, and incorporates WS-Addressing, WS-Security and WS-ReliableMessaging.
<system.serviceModel>
  <services>
    <service name="BikeStore.WcfServiceLibrary.ProductService">
      <endpoint address="" binding="basicHttpBinding" contract="BikeStore.WcfServiceLibrary.IProductService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:8733/Design_Time_Addresses/BikeStore.WcfServiceLibrary/ProductService/" />
        </baseAddresses>
      </host>
    </service>
  </services>

Behaviours

  • <behavior> elements define sets of behaviors for the endpoints and services.
  • If a <behavior> has a name attribute, then it is assigned to endpoints or services that have their behaviorConfigution attribute set equal to the name.
  • If a <behavoir> does not have a name attribute then it contributes to the default behavior of endpoints or services. Any endpoint or service that does not has a behaviorConfiguration attribute will assume these defaults.
<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="myBehavior">
         <callbackDebug includeExceptionDetailInFaults="true" />
       </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <services>
    ...
  </services>
</system.serviceModel>

Bindings

  • <binding> elements enable configuration of the endpoint bindings.
  • <binding> elements are grouped by binding type, and are associated with endpoints that have their binding attribute set equal to the binding type.
  • If a <binding> element has a name attribute then it is only associated with endpoints that have, in addition to their binding attribute set equal to the binding type, also have their bindingConfiguration attribute set equal to the name.
<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="myBindingConfiguration1" closeTimeout="00:01:00" />
      <binding name="myBindingConfiguration2" closeTimeout="00:02:00" />
      <binding closeTimeout="00:03:00" />  <!—- Default binding for basicHttpBinding -->
    </basicHttpBinding>
  </bindings>
  <services>
    ...
  </services>
</system.serviceModel>

Publishing Service Metadata

  • Add a WS-MetadataExchange (MEX) endpoint to the service
  • Add a ServiceMetadataBehavior service behavior.
<system.serviceModel>
  <services>
    <service name="BikeStore.WcfServiceLibrary.ProductService">
      ...
      <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange" />
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="True" policyVersion="Policy15" />
      </behavior>
    </serviceBehaviors>
  </behavoirs>
</system.serviceModel>
  • Clients can retrieve the metadata using a WS-Transfer GET request or an HTTP/GET request using the ?wsdl query string.
http://localhost:57481/ProductService.svc?wsdl

WCF Crib Sheet – Error Handling

SOAP Fault

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <s:Fault>
            <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher" xmlns="">a:InternalServiceFault</faultcode>
            <faultstring xml:lang="en-GB" xmlns="">The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug>configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.</faultstring>
        </s:Fault>
    </s:Body>
</s:Envelope>
  • When a .NET exception is thrown during the processing of a request, the server responds with a SOAP Fault message.
  • By default, for security reasons, the SOAP Fault message is generic and does not contain the exception details.
  • The SOAP Fault contains faultcode and a faultstring elements.

IncludeExceptionDetailsInFault

<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <s:Fault>
            <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher" xmlns="">a:InternalServiceFault</faultcode>
            <faultstring xml:lang="en-GB" xmlns="">Sequence contains no elements</faultstring>
            <detail xmlns="">
                <ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                    <HelpLink i:nil="true"></HelpLink>
                    <InnerException i:nil="true"></InnerException>
                    <Message>Sequence contains no elements</Message>
                    <StackTrace>
                        ....
                    </StackTrace>
                    <Type>System.InvalidOperationException</Type>
                </ExceptionDetail>
            </detail>
        </s:Fault>
    </s:Body>
</s:Envelope>
  • To debug a service, we can configure the service to include the exception details in the SOAP fault message.
  • Set the includeExceptionDetailInFaults config setting to true.
  • In addition to the faultcode and faultstring elements, the SOAP Fault now contains a detail element.

Explicity handling exceptions with FaultException

public ProductDto Get(int productId)
{
    try
    {
        Product product = _service.GetProduct(productId);
        return Mapper.Map<Product, ProductDto>(product);
    }
    catch (Exception ex)
    {
        throw new FaultException(
            new FaultReason(ex.Message),
            new FaultCode("Exception"));
    }
}
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <s:Fault>
            <faultcode xmlns="">s:Exception</faultcode>
            <faultstring xml:lang="en-GB" xmlns="">Sequence contains no elements</faultstring>
        </s:Fault>
    </s:Body>
</s:Envelope>
  • Error details can be returned to the client as an un-typed Fault, by throwing a new instance of System.ServiceModel.FaultException.
ProductServiceClient client = new ProductServiceClient();
ProductDto product = null;

try
{
    product = client.GetById(11);
    Console.WriteLine(product.Name);
}
catch (FaultException fex)
{
    Console.WriteLine(fex.Message);
}
finally 
{
    Console.ReadLine();
}
  • A FaultException can be caught and interrogated by the client.

Strongly Typed Faults

[DataContract]
public class ServiceFault
{
    public ServiceFault(string message)
    {
        Message = message;
    }

    [DataMember]
    public string Message { get; set; }
}

[DataContract]
public class ValidationFault : ServiceFault
{
    public ValidationFault(string message)
        : base(message)
    {
        ValidationErrors = new List<ValidationError>();
    }

    public ValidationFault(string message, List<ValidationError> validationErrors)
        : base(message)
    {
        ValidationErrors = validationErrors;
    }

    [DataMember]
    public List<ValidationError> ValidationErrors { get; set; }
}

[DataContract]
public class ValidationError
{
    public ValidationError(string property, List<string> errorMessages)
    {
        Property = property;
        ErrorMessages = errorMessages;
    }

    [DataMember]
    public string Property { get; set; }
    [DataMember]
    public List<string> ErrorMessages { get; set; }
}
  • Define one or more classes to contain the fault details.
  • The classes and properties should be decorated with the [DataContract] and [DataMember] attributes so that they are known to the client.
  • The classes can be based on System.Exception, although at the risk of revealing implementation details with the StackTrace property.
[ServiceContract(Namespace = "BikeStore.WcfServiceLibrary")]
public interface IProductService
{
    [OperationContract(Name = "GetById")]
    [FaultContract(typeof(ValidationFault))]
    ProductDto Get(int productId);
}
  • Decorate the service operation with one or more [FaultContract] attribute.
  • A [FaultContract] attribute is required for the operation to return a strongly type fault. If the attribute is omitted the service will instead return an un-typed fault.
public ProductDto Get(int productId)
{
    Product product = _service.GetProduct(productId);
    if (product == null)
    {
        throw new FaultException<ValidationFault>(new ValidationFault("Product is not valid"));
    }
    return Mapper.Map<Product, ProductDto>(product);
}
  • When a strongly typed fault exception is thrown the server will return a strongly typed fault.
  • For any other exception, and un-typed fault will be returned.
ProductServiceClient client = new ProductServiceClient();
ProductDto product = null;

try
{
    product = client.GetById(11);
    Console.WriteLine(product.Name);
}
catch (FaultException<ValidationFault> vf)
{
    Console.WriteLine(vf.Detail.Message);
}
catch (FaultException fex)
{
    Console.WriteLine(fex.Message);
}
finally
{
    Console.ReadLine();
}
  • Strongly typed faults enable the client to easily differentiate between classes of faults.
  • Strongly typed faults also enable additional error information to be sent to the client.

 

WCF Crib Sheet – Data Contract and Data Member

Data Contract Attribute

[DataContract]
public class ProductDto
{
    ...
}
  • .NET primitive types are serializable.
  • User defined types are by default not serializable.
  • The data contract attribute marks a user defined type as being serializable by the WCF data contract serializer.
  • If a user defined type is not decorated with a data contract attribute, and is a public type, then WCF will infer a data contract attribute and will serialize all members of the type.

Data Contract Inheritance

[DataContract]
public class ProductDto
{
    ...
}

[DataContract]
public class PremiumProductDto : ProductDto
{
    ...
}
  • The data contract attribute is not inheritable and so must be added to all levels in a hierarchy.

Data Member Attribute

[DataContract]
public class ProductDto
{
    [DataMember]
    public int ProductId { get; set; }

    [DataMember]
    public string Name { get; set; }
}
  • The data member attribute denotes which members of a type are serializable by the data contract serializer.
  • Can be applied on fields and properties. Best practice is to only apply to properties.
  • Properties must have both a getter and setter.
  • Can be applied on any field or property irrespective of visibility

Known Type Attribute

public class ContractService : IContractService
{
    public ContractDto GetAll()
    {
        ...
    }
}

[DataContract]
[KnownType(typeof(CreditContractDto))]
[KnownType(typeof(PrepaymentContractDto))]
public class ContractDto
{
    [DataMember]
    public int ContractId { get; set; }

    [DataMember]
    public DateTime StartDate { get; set; }

    [DataMember]
    public DateTime EndDate { get; set; }
}

[DataContract]
public class CreditContractDto : ContractDto
{
    [DataMember]
    public decimal CreditLimit { get; set; }
}

[DataContract]
public class PrepaymentContractDto : ContractDto
{
    [DataMember]
    public decimal PrepaymentAmount { get; set; }

    [DataMember]
    public PrepaymentPeriod PrepaymentPeriod { get; set; }
}
  • The known type attribute indicates the types of sub-class objects that can be expected for the data contract.

Known Type Configuration

<system.runtime.serialization>
  <dataContractSerializer>
    <declaredTypes>
      <add type="ContractDto,BikeStore.WcfServiceLibrary">
        <knownType type="CustomerContractDto,BikeStore.WcfServiceLibrary"/>
        <knownType type="PrepaymentContractDto,BikeStore.WcfServiceLibrary"/>
      </add>
    </declaredTypes>
  </dataContractSerializer>
</system.runtime.serialization>
  • An alternative to using the known type attribute is to denote known types in the service or client’s configuration file.

 

WCF Crib Sheet – Service Contract and Operation Contract

Service Contract Attribute

[ServiceContract]
public interface IProductService
{
   ...
}
  • Defines a WCF service contract.
  • Can be applied to an interface or a class. Best practice is to apply it to an interface.
  • WCF requires a class to have a parameter-less constructor.

Service Contract Names and Namespaces

[ServiceContract(Name="IBikeProductService", Namespace="BikeStore.WcfServiceLibrary")]
public interface IProductService
{     
    ...
}
  • Add a namespace to a service contract avoid potential class name collisions
  • Use the name property to change the name of the contract exposed to clients

Contract Inheritance

[ServiceContract(Namespace="BikeStore.WcfServiceLibrary")]
public interface IContractService
{
        ...
}

[ServiceContract(Namespace = "BikeStore.WcfServiceLibrary")]
public interface IPrepaymentContractService : IContractService
{
    ...
}
  • The service contract attribute is not inheritable and so must be added to all levels in a hierarchy.

Operation Contract Attribute

[ServiceContract]
public interface IProductService
{
    [OperationContract]
    ProductDto GetById(int productId);

    [OperationContract]
    IEnumerable<ProductDto> GetAll();
}
  • Indicates that a method defines an operation that is part of a service contract.
  • Methods without the attribute are not part of the service contract.
  • Can be applied to public and private methods.

Operation Overloading

[ServiceContract(Namespace="BikeStore.WcfServiceLibrary")]
public interface IProductService
{
    [OperationContract(Name="GetById")]
    ProductDto Get(int productId);

    [OperationContract(Name="GetByName")]
    ProductDto Get(string name);

    [OperationContract]
    IEnumerable<ProductDto> GetAll();
}
  • Operation names must be unique. Where the interface has overloaded methods, use the operation contract name property to alias the operation.

Client and Server Validation with Web API and Knockout

In this post I’m going to demonstrate how to implement both client and server side validation with ASP.NET Web API and Knockout. In particular I’m going to demonstrate how to convey server side binding and validation errors from the controller to the view model, and how to utilize Knockout client side validation features to display both client and server side errors in the view.

Model

My model comprises of 2 domain entities, Product and ProductCategory, with a one-to-many relationship between them.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebAPIKo.Models
{
    public class Product
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ProductId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [Required]
        [StringLength(1000)]
        public string Description { get; set; }

        [Required]
        public int ProductCategoryId { get; set; }

        // Navigation properties
        public virtual ProductCategory ProductCategory { get; set; }
    }
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebAPIKo.Models
{
    public class ProductCategory
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ProductCategoryId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        // Navigational Properties
        public virtual ICollection<Product> Products { get; set; }
    }
}

I am using code first Entity Framework as my ORM. Here’s the DbContext containing DbSets for the aforementioned entities –

using System.Data.Entity;

namespace WebAPIKo.Models
{
    public class WebAPIKoDbContext : DbContext
    {
        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<ProductCategory> ProductCategories { get; set; }
    }
}

View

My view is a simple “Create Product” form with product name and description text boxes, and a select list for product categories.

create project 2

Here’s the HTML –

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-info" id="add-panel">
            <div class="panel-heading">
                <h2 class="panel-title">Create Product</h2>
            </div>
            <div class="panel-body">
                <form role="form" data-bind="validationOptions: validationOptions">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input id="name" type="text" class="form-control" data-bind="value: product.name" placeholder="Product Name" />
                    </div>
                    <div class="form-group">
                        <label for="description">Description</label>
                        <input id="description" class="form-control" data-bind="value: product.description" placeholder="Description" />
                    </div>
                    <div class="form-group">
                        <label for="product-category">Product Category</label>
                        <select id="product-category"
                                data-bind="options: productCategories, optionsText: 'name', optionsValue: 'productCategoryId',
                           optionsCaption: '-- Select a Product Category --', value: product.productCategoryId"></select>
                    </div>
                    <button type="button" class="btn btn-primary" data-bind="click: save, enable: canSave">
                        <span class="glyphicon glyphicon-save" aria-hidden="true"></span> Add
                    </button>
                    <ul id="errors" class="error-message" data-bind="foreach: generalErrors">
                        <li><span data-bind="text: $data"></span></li>
                    </ul>
                </form>
            </div>
        </div>
    </div>
</div>

Knockout data-bind attributes are used to declare the binding of the controls to the view model.

Of note are the following –

  • The <form> has a data-bind=”validationOptions: validationOptions” attribute, which applies global validation options to all validatable controls in the form.
  • There is a “errors” <ul> element at the bottom of the form, which has a data-bind=”foreach: generalErrors” attribute.  The <ul> contains a <li> element which in turn contains a <span> with a data-bind=”text: $data” attribute. A <li> will therefore be rendered for each error message in the view model’s generalErrors ko.observableArray property. I am using this to display any errors that are not specific to a field.

Here’s some styles to accompany the form –

<style type="text/css">
    select {
        height: 30px;
        display: block;
    }

    .panel {
        width: 450px;
        margin-top: 15px;
    }

    .panel-heading {
        padding: 10px 20px;
    }

    .panel-body {
        padding: 10px 20px 10px 20px;
    }

    .error-message {
        color: red;
    }

    .error-element {
        border-color: red;
    }

    #errors {
        padding-left: 0;
        padding-top: 5px;
    }

        #errors li {
            list-style-type: none;
        }
</style>

Controller

Before I present the view model I want to discuss Web API controller actions, and in particular the HTTP response header and body that will be returned depending on whether a post/put is successful or not.

With Visual Studio 2013 we have a number of Web API controller scaffolding extensions which provide basic implementation for Web API 2 controllers and actions.

newcontroller

createcontroller2

I have selected the “Web API Controller with actions, using Entity Framework” scaffolder. I am prompted to provide the model class – Product – and the data context class – WebAPIKoDbContext. And a controller is generated with working implementations of for get, post, put, and delete actions.

Here’s the basic implementation for the post action (used for creating new products) –

// POST: api/Product
[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct([FromBody]Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Products.Add(product);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
}

This action uses Web API model binding to bind request parameters, from the body of the request, to an instance of the Product entity.

The Product entity has a number of validation attributes, which are assessed during model binding. Any validation errors are added to the ModelState object, which is an instance of System.Web.Http.ModelBinding.ModelStateDictionary. For each validation error, the property name is added to the ModelState’s Keys collection and the error description is added to the ModelState’s Values collection. Each item in the Values collection is actually an array of strings, thus enabling more than one error description per Key.

If there are model binding or validation errors, the action returns BadRequest(ModelState). This results in a HTTP 400 response being sent to the client, along with the response body containing a JSON serialization of a Message string and the ModelState object. Here are some examples of the response body –

In the first example the model binding was unsuccessful as the parameters in the request body did not match any of the Product properties. The model binder was not able to generate the product object.

{   "Message":"The request is invalid.",
    "ModelState":{
        "product":["Error converting value \"ww\" to type 'WebAPIKo.Models.Product'. Path '', line 1, position 4."]}
}

In this second example, the model binder was able to generate the product object, but the name and description properties failed validation as no values were posted for them, whilst they are required.

{   "Message":"The request is invalid.",
    "ModelState":{
        "product.Name":["The Name field is required."],
        "product.Description":["The Description field is required."]}}

In addition to performing this validation on the server, I will also be performing model validation on the client. Validation is one example of where it is necessary to deviate from the DRY principal. If we were only to validate on the server then the user would have to submit the form and wait for a response before being notified of validation errors. This could be very frustrating for the user, and so it is better to have the browser perform validation whilst the user is interacting with the form. But the client side validation should be an addition to rather than a replacement for the server side validation. Firstly, because we cannot guarantee that the request will be correctly formed, and secondly, because not all validation can easily be performed on the client.

For example, if we have such a business rule stating that product names must be unique, and we have many products then we may need to validate the product against this rule on the server. If the product fails this rule we need to communicate this back to the client, and we can utilize the ModelState object to do this. We can also utilize the ModelState object to convey non-field-specific validation errors as shown below.

ModelState.AddModelError("product.Name", "Product name is already in use");

ModelState.AddModelError("General", "General error 1");
ModelState.AddModelError("General", "General error 2");

And resulting in the following response body –

{   "Message":"The request is invalid.",
    "ModelState":{
        "product.Name":["Product name is already in use"],
        "General":["General error 1","General error 2"]}}

Of note is that because we added 2 model errors with the “General” key, then we have 2 items in the array of error descriptions.

One further thing we need to account for in handling errors, is that it is possible that an error occurs on the server during the processing of the request. For example, there may be a network issue with the application temporarily not being able to connect to the database. In this case a HTTP 500 response will be generated with a response body similar to the following –

{   "Message":"An error has occurred.",
    "ExceptionMessage":"An exception has occurred",
    "ExceptionType":"System.Exception"}

So when we have a validation error or exception then we get a HTTP 400 or 500 response with a response body that always contains a “Message” property, and optionally contains a “ModelState” object. Our client code will therefore need to trap HTTP 400 and 500 responses, and parse the “ModelState” object if one exists. And if not, display the “Message”.

View Model

ko.observable.appendError

Knockout validation, by default, appends validation attributes and an error message span after each input control that is bound to a validateable property. For example, the view incorporates the following input control which is bound to the product.name property –

<input id="name" type="text" class="form-control" data-bind="value: product.name" placeholder="Product Name" />

After the bindings are applied, the following HTML is generated by Knockout –

<input id="name" type="text" class="form-control" data-bind="value: name" placeholder="Product Name" title="This field is required." data-orig-title="">
<span class="error-message" style="display: none;"></span>

When the user interacts with the view, entering or modifying data, the view model’s ko.observable properties are automatically updated. The Knockout validation library extends the ko.observable type to include an error property, and a setError method. Each validateable ko.observable property is validated according to it’s validation rules, and the setError method is used to assign a validation error to the error property. The setError method overwrites the value of the error property, and assigns the ko.observable as being not valid.

The mechanics of displaying client validation errors in the view is therefore available out-of-the-box with Knockout validation. We can also hook into these mechanics in order to display validation errors returned from the server.

The first thing I have done to hook into these mechanics is to extend the ko.observable type to include an appendError function, which appends new errors onto existing ones rather than overwriting them. This is needed because there is the possibility of more than one error per property being returned from the server.

///////////////////////////////////////////////////////////////////
// ko.observable.appendError

ko.observable.fn.appendError = function (error) {
    var thisError = this.error();
    if (thisError) {
        this.setError(thisError += '. ' + error);
    }
    else {
        this.setError(error)
    };
};

ProductCategory and ProductCategoryList

The productCategory and productCategoryList types contain properties and functions for the retrieval of a list of product categories from the server. The product categories are used to populate the form’s product category select control.

///////////////////////////////////////////////////////////////////
// ProductCategory

var productCategory = function (productCategoryId, name) {
    var self = this;

    // Properties
    self.productCategoryId = productCategoryId;
    self.name = name;
}

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

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

    self.get = function (callBack) {
        $.ajax({
            url: '/api/productCategory',
            type: 'get',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $.each(data, function (key, value) {
                    self.productCategories.push(new productCategory(value.ProductCategoryId, value.Name));
                });

                if (typeof callBack !== "undefined") {
                    callBack();
                };
            }
        });
    }
}

ProductVM

I will be binding an instance of ProductVM to the create product view. It is our view model object.

ProductVM  has a self.product object, which is a wrapper for the name, description, and productCategoryId ko.observable properties. I am using product as a wrapper for these properties as it makes the properties easier to work with as a group.

self.product = {
    name: ko.observable(null),
    description: ko.observable(null),
    productCategoryId: ko.observable(0)
}

ProductVM also has self.productCategories which is a ko.observableArray property for storing product categories. An array of product categories is passed into the ProductVM’s constructor during initialization, and this array is in turn passed into the ko.observableArray’s constructor. self.productCategories is used to populate the view’s product category select list.

self.productCategories = ko.observableArray(productCategories);

Next I have the assignment of Knockout validation validation rules to the ko.observable product properties. And the creation of a validation group, which enables us to display, hide, or remove all validation errors.

self.product.name.extend({
    required: true,
    maxLength: 100
});

self.product.description.extend({
    required: true,
    maxLength: 1000
});

self.product.productCategoryId.extend({
    required: true
});

self.errors = ko.validation.group(self.product);

I then define self.generalErrors which is a ko.observableArray that will store all validation errors that are not specific to one of the validatable properties. This array is bound to the errors list towards the bottom of the view using a foreach binding. As such, when it is populated with one or more validation errors, a list item element is created for each, and the messages are displayed.

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

The next thing I do is define some validation options. These options are bound, using a validationOptions binding to the form. They are therefore applicable to all input controls in the form.

self.validationOptions = {
    decorateInputElement: true,
    errorElementClass: 'error-element',
    errorMessageClass: 'error-message'
};

Next we have some properties that manage state. The first of these, self.isSaving, is set to true at the start of a save, and then set to false once the save is complete. The next, self.isValid, is a ko.computed property that is set to true when there are no validation error in the errors group, and false when there are. The third property, self.canSave, is a ko.computed property that is set to true when self.isValid, and !self.isSaving. self.canSave is bound to the enable attribute of the view’s add button.

self.isSaving = ko.observable(false);

self.isValid = ko.computed(function () {
    return self.errors().length == 0;
});

self.canSave = ko.computed(function () {
    return self.isValid() && !self.isSaving();
});

The final thing we have in the ProductVM is the save method.

If there are no validation errors the save method sets self.isSaving to true, which has the effect of disabling the view’s add button. This stops the user from invoking concurrent saves. The save method then uses ko.toJSON to generate a JSON string containing the product properties.

The save method then performs an ajax POST to the /api/products url, passing the JSON string in the request body, and if the ajax request is successful then self.isSaving to false.

However, if the ajax request is not successful, and a HTTP 400 response is returned from the server then the following logic is performed –

  • Check to see if there is a ModelState object in the response body.
  • If there is a ModelState object then loop through the keys, and for each key loop through the errors.
  • For each error, if the key matches a validateable property name then append the error to the property.
  • If the key does not match a property name then push the error to the generalErrors observableArray.
  • If the response body does not contain a ModelState object – which is optional – then push the Message string – which is required – to the generalErrors array.

And if a HTTP 500 response is returned then the following logic is performed –

  • The response body will not contain a ModelState object. Push the Message string to the generalErrors array.
self.save = function () {
    if (self.errors().length == 0) {
        self.isSaving(true);

        var dataObject = ko.toJSON(self.product);

        $.ajax({
            url: '/api/products',
            type: 'post',
            data: dataObject,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                self.isSaving(false);
            },
            statusCode: {
                400: function (data) {
                    if (typeof data.responseJSON.ModelState !== 'undefined') {
                        $.each(data.responseJSON.ModelState, function (key, errors) {
                            $.each(errors, function (index, error) {
                                switch (key) {
                                    case 'Name':
                                        self.product.name.appendError(error);
                                        break;
                                    case 'Description':
                                        self.product.description.appendError(error);
                                        break;
                                    case 'ProductCategory':
                                        self.product.productCategoryId.appendError(error);
                                        break;
                                    default:
                                        self.generalErrors.push(error);
                                        break;
                                };
                            });
                        });
                    }
                    else {
                        self.generalErrors.push(data.responseJSON.Message);
                    };
                },
                500: function (data) {
                    self.generalErrors.push(data.statusText + '. Please try again.');
                }
            }
        });
    }
    else {
        self.errors.showAllMessages(true);
    }
};

Because we are appending and pushing the errors to the validatable ko.observable properties and the generalErrors ko.observableArray, and these are bound to the form, then the validation errors will automatically be displayed in the appropriate places in the view.

This is what we will see.

createformerrors

Kick-off

The final thing I have in the view model is the code to kick it all off –

/////////////////////////////////////////////////////////////////
// Let's kick it all off

var productCategoryList = new productCategoryList();

productCategoryList.get(function () {
    var vm = new productVM(productCategoryList.productCategories());
    ko.applyBindings(vm, $addPanel[0]);
    vm.errors.showAllMessages(false);
});

 

For completeness, here’s the full view model.

<script type="text/javascript">
    ///////////////////////////////////////////////////////////////////
    // ko.observable.appendError

    ko.observable.fn.appendError = function (error) {
        var thisError = this.error();
        if (thisError) {
            this.setError(thisError += '. ' + error);
        }
        else {
            this.setError(error)
        };
    };

    $(function () {
        var $addPanel = $('#add-panel');
        ///////////////////////////////////////////////////////////////////
        // ProductCategory

        var productCategory = function (productCategoryId, name) {
            var self = this;

            // Properties
            self.productCategoryId = productCategoryId;
            self.name = name;
        }

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

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

            self.get = function (callBack) {
                $.ajax({
                    url: '/api/productCategory',
                    type: 'get',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        $.each(data, function (key, value) {
                            self.productCategories.push(new productCategory(value.ProductCategoryId, value.Name));
                        });

                        if (typeof callBack !== "undefined") {
                            callBack();
                        };
                    }
                });
            }
        }

        ///////////////////////////////////////////////////////////////////
        // ProductVM

        var productVM = function (productCategories) {
            var self = this;

            // Properties

            self.product = {
                name: ko.observable(null),
                description: ko.observable(null),
                productCategoryId: ko.observable(0)
            }

            self.productCategories = ko.observableArray(productCategories);

            // Validation

            self.product.name.extend({
                required: true,
                maxLength: 100
            });

            self.product.description.extend({
                required: true,
                maxLength: 1000
            });

            self.product.productCategoryId.extend({
                required: true
            });

            self.errors = ko.validation.group(self.product);

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

            self.validationOptions = {
                decorateInputElement: true,
                errorElementClass: 'error-element',
                errorMessageClass: 'error-message'
            };

            // State

            self.isSaving = ko.observable(false);

            self.isValid = ko.computed(function () {
                return self.errors().length == 0;
            });

            self.canSave = ko.computed(function () {
                return self.isValid() && !self.isSaving();
            });

            // Methods

            self.save = function () {
                if (self.errors().length == 0) {
                    self.isSaving(true);

                    var dataObject = ko.toJSON(self.product);

                    $.ajax({
                        url: '/api/products',
                        type: 'post',
                        data: dataObject,
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            self.isSaving(false);
                        },
                        statusCode: {
                            400: function (data) {
                                if (typeof data.responseJSON.ModelState !== 'undefined') {
                                    $.each(data.responseJSON.ModelState, function (key, errors) {
                                        $.each(errors, function (index, error) {
                                            switch (key) {
                                                case 'product.Name':
                                                    self.product.name.appendError(error);
                                                    break;
                                                case 'product.Description':
                                                    self.product.description.appendError(error);
                                                    break;
                                                case 'product.ProductCategory':
                                                    self.product.productCategoryId.appendError(error);
                                                    break;
                                                default:
                                                    self.generalErrors.push(error);
                                                    break;
                                            };
                                        });
                                    });
                                }
                                else {
                                    self.generalErrors.push(data.responseJSON.Message);
                                };
                            },
                            500: function (data) {
                                self.generalErrors.push(data.statusText + '. Please try again.');
                            }
                        }
                    });
                }
                else {
                    self.errors.showAllMessages(true);
                }
            };
        }

        /////////////////////////////////////////////////////////////////
        // Let's kick it all off

        var productCategoryList = new productCategoryList();

        productCategoryList.get(function () {
            var vm = new productVM(productCategoryList.productCategories());
            ko.applyBindings(vm, $addPanel[0]);
            vm.errors.showAllMessages(false);
        });
    });
</script>

 

Create, Update, and Delete with KoGrid

In my previous post I demonstrated how to implement server-side paging with KoGrid and Knockout within the context of an ASP.NET web application, and utilizing MVC and WebApi controllers. In this post I’m going to demonstrate how to extend the grid to enable the user to create, update, and delete records.

I’m going to add an ‘action’ column to the grid, with edit and delete buttons for each record. And I’m going to add an add button.

kogrid2

When the user clicks on a record’s edit button, an edit panel is displayed. The save button is initially disabled, and will be enabled if the user changes the details and all fields are valid. When the user clicks on the save button the changes will be saved, the edit panel will be hidden, and the grid will be refreshed.

kogrid3

When the user clicks on the add button, an add panel is displayed. The add button is initially disabled and will be enabled when the user has entered valid values for all fields. When the user clicks on the add button, the new record is added, the add panel is hidden, and the grid is refreshed.

kogrid4

And when the user clicks on a delete button, the record will be deleted and the grid refreshed.

As per my previous post I’m going to present the solution in the following order –

  1. Model
  2. Controller
  3. View
  4. ViewModel

1. Model

Domain Model

The domain model remains unchanged, with a one-to-many relationship between product categories and products.

ProductCategory.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebAPIKo.Models
{
    public class ProductCategory
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ProductCategoryId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        // Navigational Properties
        public virtual ICollection<Product> Products { get; set; }
    }
}

Product.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebAPIKo.Models
{
    public class Product
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ProductId { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [Required]
        [StringLength(1000)]
        public string Description { get; set; }

        [Required]
        public int ProductCategoryId { get; set; }

        // Navigation properties
        public virtual ProductCategory ProductCategory { get; set; }
    }
}

WebApiDbContext.cs

using System.Data.Entity;

namespace WebAPIKo.Models
{
    public class WebAPIKoDbContext : DbContext
    {
        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<ProductCategory> ProductCategories { get; set; }
    }
}

Data Transfer Objects (DTOs)

ProductCategoryDTO.cs

When editing and adding products we need to allow the user to select a product category from a list. We therefore need a ProductCategoryDTO class to transfer product category details to the view model.

namespace WebAPIKo.Models
{
    public class ProductCategoryDTO
    {
        public int ProductCategoryId { get; set; }
        public string Name { get; set; }
    }
}

ProductDTO.cs

I have added ProductCategoryId to the ProductDTO class, as we now need to uniquely identify a product’s category when editing the product.

namespace WebAPIKo.Models
{
    public class ProductDTO
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int ProductCategoryId { get; set; }
        public string ProductCategoryName { get; set; }
    }
}

ProductListDTO.cs

The ProductListDTO class has not changed. The grid still requires a page of products and a count of the total number of products matching the selected filter.

using System.Collections.Generic;

namespace WebAPIKo.Models
{
    public class ProductListDTO
    {
        public int ProductCount { get; set; }
        public List<ProductDTO> PageOfProducts { get; set; }
    }
}

2. Controller

HomeController.cs

The view/view model – ProductKoGrid.cshtml – is served up by the home controller.

using System.Web.Mvc;

namespace WebAPIKo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult ProductKoGrid()
        {
            return View();
        }
    }
}

ProductController.cs

In addition to GetProducts, the Product controller has the following actions –

  • GetProduct(int id)
    • Queries the domain model for a Product with the specified id.
    • If not found then returns a 404 (not found) response.
    • If found the returns a 200 (OK) response along with a ProductDTO class containing the product details.
  • PutProduct([FromBody]Product product)
    • Updates an existing product.
    • The [FromBody] attribute tells the controller to map the values contained in the request body to a Product object.
    • If the product is not valid a 400 (bad request) response is returned.
    • An attempt is made to save the changes to the product. If successful a 204 (success, no content) response is returned.
    • If a DbUpdateConcurrencyException occurs whilst saving the changes then either a 404 (not found) response is returned if the product does not exist on the database (it may have been deleted by another user), or a 500 (internal server error) is returned if the product does exist.
  • PostProduct([FromBody]Product product)
    • Adds a new product.
    • The [FromBody] attribute tells the controller to map the values contained in the request body to a Product object.
    • If the product is not valid a 400 (bad request) response is returned.
    • An attempt is made to add the product. If successful a 201 (created) response is returned.
  • DeleteProduct(int id)
    • Queries the domain model for a Product with the specified id.
    • If not found then returns a 404 (not found) response.
    • If found then deletes the product and returns a 200 (OK) response.
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Dynamic;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using WebAPIKo.Models;

namespace WebAPIKo.Controllers
{
    public class ProductsController : ApiController
    {
        private WebAPIKoDbContext db = new WebAPIKoDbContext();

        // GET: api/Product
        public IHttpActionResult GetProducts([FromUri]int page, [FromUri]int pageSize, [FromUri]string filter, [FromUri]string sort)
        {       
            ProductListDTO dto = new ProductListDTO();

            IQueryable<Product> query = db.Products;

            if (filter != null)
            {
                if (filter.Contains(':'))
                {
                    string[] filterArray = filter.Split(':');
                    switch (filterArray[0].ToLower())
                    {
                        case "name":
                            query = query.Where(p => p.Name.Contains(filterArray[1].Trim()));
                            break;
                        case "description":
                            query = query.Where(p => p.Description.Contains(filterArray[1].Trim()));
                            break;
                    }
                }
                else
                {
                    query = query.Where(p => p.Name.Contains(filter.Trim()) || p.Description.Contains(filter.Trim()));
                }
            }

            dto.ProductCount = query.Count();

            query = query.OrderBy(sort == null ? "name asc" : sort).Skip((page - 1) * pageSize).Take(pageSize);

            dto.PageOfProducts = query.Select(p => new ProductDTO()
                {
                    ProductId = p.ProductId,
                    Name = p.Name,
                    Description = p.Description,
                    ProductCategoryId = p.ProductCategoryId,
                    ProductCategoryName = p.ProductCategory.Name
                }
                ).ToList(); 

            return Ok(dto);
        }

        // GET: api/Product/5
        [ResponseType(typeof(Product))]
        public IHttpActionResult GetProduct(int id)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            return Ok(new ProductDTO() { ProductId = product.ProductId, Name = product.Name, ProductCategoryId = product.ProductCategoryId });
        }

        // PUT: api/Product/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutProduct([FromBody]Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(product.ProductId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Product
        [ResponseType(typeof(Product))]
        public IHttpActionResult PostProduct([FromBody]Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Products.Add(product);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
        }

        // DELETE: api/Product/5
        [ResponseType(typeof(Product))]
        public IHttpActionResult DeleteProduct(int id)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            db.Products.Remove(product);
            db.SaveChanges();

            return Ok(product);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool ProductExists(int id)
        {
            return db.Products.Count(e => e.ProductId == id) > 0;
        }
    }
}

ProductCategoryController.cs

The ProductCategoryController class is an ApiController, containing a single action – GetProductCategories – which returns a list of ProductCategoryDTO objects.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebAPIKo.Models;

namespace WebAPIKo.Controllers
{
    public class ProductCategoryController : ApiController
    {
        private WebAPIKoDbContext db = new WebAPIKoDbContext();

        // GET: api/ProductCategory
        public IHttpActionResult GetProductCategories()
        {
            db.Configuration.ProxyCreationEnabled = false;

            List<ProductCategoryDTO> dto = new List<ProductCategoryDTO>();

            dto = db.ProductCategories.Select(pc =>
                new ProductCategoryDTO()
                {
                    ProductCategoryId = pc.ProductCategoryId,
                    Name = pc.Name
                }
                ).ToList();

            return Ok(dto);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

3. View

HTML

When the add or edit panel is displayed, we need to simulate modality by disabling the rest of the page. This is achieved by displaying an opaque <div> over the whole page with a z-order that is greater than all elements on the page except for the panel.

<div id="disabling-div"></div>

I have added a footer to the list panel. The footer contains an add button, which has it’s click event bound to the view models “get” method.

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h3 class="panel-title list-panel-title">Products</h3>
                <button type="button" class="btn btn-default btn-md refresh-button" data-bind="click: get">
                    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Refresh
                </button>
            </div>
            <div class="panel-body">
                <div class="gridStyle" data-bind="koGrid: gridOptions"></div>
            </div>
            <div class="panel-footer">
                <button type="button" class="btn btn-primary btn-md" data-bind="click: add">
                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add
                </button>
            </div>
            <img src="~/Content/Images/ajax-loader.gif" class="loading-indicator" id="loading-indicator" />
        </div>
    </div>
</div>

I have added 2 separate panels, containing the add and edit forms. It does not matter where on the page these panels are placed as initially they will be hidden and then will be displayed at an absolute position using a SlideDown transition.

Each panel is comprised of the following –

  • A close icon in the panel header, which has it’s click event bound to the respective view model’s cancel() method.
  • A form containing form controls that are bound to the appropriate view model’s properties.
  • The id field is hidden in the add panel, and read-only in the edit.
  • A select control is used to display the product category options. The options are populated from the view model’s productCategories field. We will see in the next section that this field is a ko.observableArray containing productCategory objects. The selected value is bound to the view model’s productCategoryId property.
  • A save button bound to the view model’s cancel() method.
  • The add form has an add button bound to the add view model’s add() method. This button is initially disabled, and will be enabled when the user has completed entering valid values.
  • The edit form has an edit button bound to the edit view model’s update() method. This button is initially disabled and will be enabled when the user has changed at least one value, and all values are valid.
<div class="panel panel-info add-panel" id="add-panel">
    <div class="panel-heading">
        <span class="closeIcon"><span class="glyphicon glyphicon-remove" data-bind="click: cancel"></span></span>
        <h2 class="panel-title">Add New Product</h2>
    </div>
    <div class="panel-body">
        <form id="add-form" role="form">
            <div class="form-group">
                <input id="add-id" type="hidden" class="form-control" data-bind="value: productId" />
            </div>
            <div class="form-group">
                <label for="add-name">Name</label>
                <input id="add-name" type="text" class="form-control" data-bind="value: name" placeholder="Product Name" />
            </div>
            <div class="form-group">
                <label for="add-description">Description</label>
                <input id="add-description" class="form-control" data-bind="value: description" placeholder="Description" />
            </div>
            <div class="form-group">
                <label for="add-product-category">Product Category</label>
                <select id="add-product-category"
                        data-bind="options: productCategories, optionsText: 'name', optionsValue: 'productCategoryId',
                           optionsCaption: '-- Select a Product Category --', value: productCategoryId"></select>
            </div>
            <button type="button" class="btn btn-primary" data-bind="click: add, enable: canSave">
                <span class="glyphicon glyphicon-save" aria-hidden="true"></span> Add
            </button>
            <button type="button" class="btn btn-primary" data-bind="click: cancel">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Cancel
            </button>
        </form>
    </div>
</div>

<div class="panel panel-info edit-panel" id="edit-panel">
    <div class="panel-heading">
        <span class="closeIcon"><span class="glyphicon glyphicon-remove" data-bind="click: cancel"></span></span>
        <h2 class="panel-title">Edit Product</h2>
    </div>
    <div class="panel-body">
        <form id="edit-form" role="form">
            <div class="form-group">
                <label for="edit-id">Id</label>
                <input id="edit-id" type="hidden" class="form-control" data-bind="value: productId" />
                <p data-bind="text: productId"></p>
            </div>
            <div class="form-group">
                <label for="edit-name">Name</label>
                <input id="edit-name" type="text" class="form-control" data-bind="value: name" placeholder="Product Name" />
            </div>
            <div class="form-group">
                <label for="edit-description">Description</label>
                <input id="edit-description" class="form-control" data-bind="value: description" placeholder="Description" />
            </div>
            <div class="form-group">
                <label for="edit-product-category">Product Category</label>
                <select id="add-product-category"
                        data-bind="options: productCategories, optionsText: 'name', optionsValue: 'productCategoryId',
                           optionsCaption: '-- select a Product Category --', value: productCategoryId"></select>
            </div>
            <button type="button" class="btn btn-primary" data-bind="click: update, enable: canSave">
                <span class="glyphicon glyphicon-save" aria-hidden="true"></span> Save
            </button>
            <button type="button" class="btn btn-primary" data-bind="click: cancel">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Cancel
            </button>
        </form>
    </div>
</div>

CSS

I have made some small changes to the .gridStyle, kg*, and .listPanel styles, which style the grid and grid panel.

The .addPanel and .editPanel styles, as their names suggest style the add and edit panels. The panels are initially hidden and are positioned towards the top of the page. The z-index is set at 9999. This ensures that they are displayed over the disabling div.

The .closeIcon style is used to position remove glyphicons towards the right hand side of the add and edit panel headers. This simulates a modal close button.

The #disabling-div style positions the disabling div across the whole page, sets it opacity to 50%, and it’s z-index to 1001. The div when visible should then be displayed over all page elements except for the add and edit panels.

<style type="text/css">
    select {
        height: 30px;
        display: block;
    }

    .panel-heading {
        padding: 10px 20px;
    }

    .panel-body {
        padding: 20px 20px 10px 20px;
    }

    .gridStyle {
        border: 1px solid rgb(212,212,212);
        width: 100%;
        height: 300px;
        margin: auto;
    }

    .kgColMenu {
        width: 200px;
    }

        .kgColMenu input[type=text] {
            width: 100%;
        }

    .kgColList {
        padding-left: 25px;
    }

    .kgColListItem label {
        width: 100%;
    }

    .row-button {
        margin-top: 6px;
    }

    .closeIcon {
        position: absolute;
        right: 10px;
        top: 10px;
        font-weight: bold;
        font-family: sans-serif;
        cursor: pointer;
    }

    .add-panel, .edit-panel {
        position: absolute;
        top: 105px;
        width: 400px;
        display: none;
        margin: auto;
        left: 50%;
        margin-left: -200px;
        z-index: 9999;
    }

    .list-panel {
        margin-top: 20px;
    }

        .list-panel .panel-heading {
            overflow: auto;
            padding: 5px 20px;
        }

        .list-panel .panel-title {
            float: left;
            margin-top: 10px;
        }

        .list-panel .panel-footer {
            padding: 5px 20px;
        }

        .list-panel .refresh-button {
            float: right;
        }

    .loading-indicator {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -26px;
        margin-top: -26px;
        display: none;
        z-index: 9999;
    }

    #disabling-div {
        display: none;
        z-index: 1001;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: white;
        opacity: .50;
        filter: alpha(opacity=50);
    }
</style>

4. ViewModel

Notifier

To keep the code modular, I have created a separate view model for each of the add, edit, and list panels. I want to keep these view models independent, with no knowledge of each other.

For example, the edit view model contains an update() method that communicates changes to the controller via an ajax post. After a successful update, we want the product list to be refreshed, and the list view model contains a get() method to achieve this. We could have the edit view model directly call the list view model’s get() method. But the edit view model would now be dependent on the list view model, making changes more difficult to implement.

A simple answer to our problem is provided by Knockout.

ko.subscribable, is the base object that all Knockout observables derive from. It contains a subscribe() method which enables subscribers to register a function to be called when an event occurs. The subscribe() method accepts three parameters –

  • callBack – the function that is called whenever the event notification occurs.
  • target (optional) – defines the value of this in the callback function.
  • event (optional; default is “change”) – the name of the event.

ko.subscribable also contains a notifySubscribers() method which accepts two parameters –

  • valueToNotify (optional) – value to pass through to the subscribers.
  • event – the names of the event.

I have defined a notifier object to be a global instance of ko.subscribable(), and I have defined some event names –

///////////////////////////////////////////////////////////////////
// Notifier
var notifier = new ko.subscribable();
var PRODUCT_UPDATED = "PRODUCT_UPDATED";
var INVOKE_ADD = "INVOKE_ADD";
var INVOKE_EDIT = "INVOKE_EDIT";

And for our example where we want the list view model’s get() method to be called on successful completion of the edit view model’s update() – the list view model registers it’s get() method using the following code –

notifier.subscribe(self.get, null, PRODUCT_UPDATED);

And the edit view model raises the notification on successful completion of the update() method using the following code –

notifier.notifySubscribers(null, PRODUCT_UPDATED);

Transitions

The add and edit panels are initially hidden. When the user chooses to add a new record, or edit an existing record, we need to reveal the relevant panel, whilst displaying the disabling div that obscures the rest of the view.

I have created a transition object to encapsulate this logic. It has 2 methods – show() and hide(), both of which receive a target and an optional callBack function.

///////////////////////////////////////////////////////////////////////////
// Transitions

var transition = {

    duration: 200,

    show: function (target, callBack) {
        if (target.is(':hidden')) {
            $disablingDiv.show();
            target.slideDown(transition.duration, function () {
                target.find('input[type!=hidden]:first').focus();
                if (typeof callBack !== "undefined") {
                    callBack();
                }
            });
        }
        else if (typeof callBack !== "undefined") {
            callBack();
        }
    },

    hide: function (target, callBack) {
        if (target.is(':visible')) {
            $disablingDiv.hide();
            target.slideUp(transition.duration, callBack);
        }
        else if (typeof callBack !== "undefined") {
            callBack();
        }
    }
}

ProductCategory and ProductCategoryList

The productCategoryList object is comprised of a ko.observableArray, and a get() method.

The get() method retrieves product categories via an ajax get call, and for each creates an instance of productCategory and pushes it to the ko.observableArray.

I have added callBack as an optional argument to the get() method, and will be using this to ensure that a complete list of product categories has been populated prior to binding the add and edit view models.

///////////////////////////////////////////////////////////////////
// ProductCategory

var productCategory = function (productCategoryId, name) {
    var self = this;

    // Properties
    self.productCategoryId = productCategoryId;
    self.name = name;
}

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

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

    self.get = function (callBack) {
        $.ajax({
            url: '/api/productCategory',
            type: 'get',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $.each(data, function (key, value) {
                    self.productCategories.push(new productCategory(value.ProductCategoryId, value.Name));
                });

                if (typeof callBack !== "undefined") {
                    callBack();
                };
            }
        });
    }
}

Product

The product object type is a data container, with ko.observable properties. The list view model has a ko.observableArray containing product objects, which is bound to the grid. Also, as discussed in the next section, the add product and edit product view models are based on the product type.

///////////////////////////////////////////////////////////////////
// Product

var product = function (data) {
    var self = this;

    self.productId = ko.observable(data.productId || 0);
    self.name = ko.observable(data.name || null);
    self.description = ko.observable(data.description || null);
    self.productCategoryId = ko.observable(data.productCategoryId || 0);
    self.productCategoryName = ko.observable(data.productCategoryName || null);
}

ProductVM

The productVM object type is an extension of product, and is comprised of data, configuration properties, and methods shared by the add and edit product view models.

///////////////////////////////////////////////////////////////////
// ProductVM

var productVM = function (productCategories, panel) {
    var self = this;

    // Functional Inheritance

    ko.utils.extend(self, new product({}));

    // Properties

    self.productCategories = ko.observableArray(productCategories);

    // Validation

    self.name.extend({
        required: true,
        maxLength: 100
    });

    self.description.extend({
        required: true,
        maxLength: 1000
    });

    self.productCategoryId.extend({
        required: true
    });

    self.errors = ko.validation.group([self.productId, self.name, self.description, self.productCategoryId]);

    // State

    self.hasChanged = ko.observable(false);
    self.isSaving = ko.observable(false);

    self.isValid = ko.computed(function () {
        return self.errors().length == 0;
    });

    self.canSave = ko.computed(function () {
        return self.isValid() && self.hasChanged() && !self.isSaving();
    });

    // Subscriptions

    self.name.subscribe(function (value) {
        self.hasChanged(true);
    });

    self.description.subscribe(function (value) {
        self.hasChanged(true);
    });

    self.productCategoryId.subscribe(function (value) {
        self.hasChanged(true);
    });

    // Methods

    self.initialize = function (data) {
        if (data != null) {
            self.productId(data.productId() || 0);
            self.name(data.name() || null);
            self.description(data.description() || null);
            self.productCategoryId(data.productCategoryId() || 0);
        }
        else {
            self.errors.showAllMessages(false);
        }

        self.hasChanged(false);

        self.show();
    };

    self.cancel = function () {
        self.hide();
    };

    self.show = function () {
        transition.show(panel);
    }

    self.hide = function () {
        // Hide and tidy up
        transition.hide(panel, function () {
            self.productId(0);
            self.name(null);
            self.description(null);
            self.hasChanged(false);
            self.errors.showAllMessages(false);
        });
    }
}

productVM is comprised of the following –

  • A constructor that takes 2 arguments – productCategories which is a collection of productCategory objects, and panel which is the JQuery reference to either the add or edit panel.
  • A self.productCategories property of type ko.observableArray. The productCategories argument is passed into it’s constructor, and it is used to populate a select list when the view model is bound to the view.
  • Extension calls which add Knockout validation configuration information to the product properties.
  • A Knockout validation group, self.errors, containing the properties that require validation.
  • Properties used for tracking state –
    • self.hasChanged – tracks whether one or more properties have been changed.
    • self.isSaving – tracks whether the view model is currently saving. This is necessary as the save operations are asynchronous.
    • self.isValid – tracks whether the product is valid. This is a computed based on the number of validation errors in the self.errors validation group.
    • self.canSave – tracks whether the product can be saved, and is computed as self.isValid() && self.hasChanged && !self.isSaving.
  • Subscriptions which assign functions that set self.hasChanged(true) in response to a change to one of the product properties.
  • A self.initialize method that initializes the state of the view model, including setting product properties. The reason I have an initialize method to set the state, rather than using the view model’s constructor, is that I want to create a single instance of each the add and edit view models and bind them against the view once. But then I want to reuse these view models for adding and editing products consecutively without having to rebind.
  • A self.cancel() function which is bound to the add and edit panel cancel buttons. The self.cancel function calls the self.hide() function.
  • A self.show() function which utilizes the transition object to display the panel. I will describe how and when this method gets executed when I discuss the productAddVM and productEditVM implementations.
  • A self.hide() function which utilizes the transition object to hide the panel, and includes some tidy-up code in a callBack function.

ProductAddVM

productAddVM is the view model that is bound to the add product panel. It extends productVM, and adds in functionality that is specific to adding products.

///////////////////////////////////////////////////////////////////
// ProductAddVM

var productAddVM = function (productCategories) {
    var self = this;

    var panel = $addPanel;

    // Functional Inheritance

    ko.utils.extend(self, new productVM(productCategories, panel));

    // Subscriptions

    notifier.subscribe(self.initialize, null, INVOKE_ADD);

    // Methods

    self.add = function () {

        if (self.errors().length == 0) {

            self.isSaving(true);

            var dataObject = ko.toJSON(this);

            $.ajax({
                url: productsUri,
                type: 'post',
                data: dataObject,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    self.isSaving(false);

                    self.hide();

                    notifier.notifySubscribers(null, PRODUCT_UPDATED);
                }
            });
        }
        else {
            self.errors.showAllMessages();
        }
    };
}

productAddVM is comprised of the following –

  • A constructor that takes a productCategories argument, which is then passed through to the base productVM and assigned to self.productCategories. I have taken the decision to retrieve a set of product categories from the server when the page is initialized, and then pass these into the productAddVM when they are constructed. I am assuming that the product categories will not be changed during the life-time of the page.
  • A JQuery reference to the add panel. This is also passed through to the base productVM and used by the show and hide methods.
  • A notifier subscription, which requests the execution of the self.initialize method when the INVOKE_ADD event notification is triggered. The list view model will trigger this event when the user clicks on the grid’s add button.
  • An update() method which utilizes a ajax put to pass the new product details to the server. On successful execution the method hides the panel and triggers the PRODUCT_UPDATED event notification.

ProductEditVM

productEditVM is bound to the edit panel, and also extends productVM. It contains functionality that is specific to editing products.

///////////////////////////////////////////////////////////////////
// ProductEditVM

var productEditVM = function (productCategories) {
    var self = this;

    var panel = $editPanel;

    // Functional Inheritance

    ko.utils.extend(self, new productVM(productCategories, panel));

    // Subscriptions

    notifier.subscribe(self.initialize, null, INVOKE_EDIT);

    // Methods

    self.update = function () {
        if (self.errors().length == 0) {

            self.isSaving(true);

            var dataObject = ko.toJSON(this);

            $.ajax({
                url: productsUri,
                type: 'put',
                data: dataObject,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    self.isSaving(false);

                    self.hide();

                    notifier.notifySubscribers(null, PRODUCT_UPDATED);
                }
            });
        }
        else {
            self.errors.showAllMessages();
        }
    };
}

It is comprised of the following –

  • A constructor that takes a productCategories argument, which is passed through to the base productVM.
  • A JQuery reference to the edit panel. This is also passed through to the base productVM and used by the show and hide methods.
  • A notifier subscription, which requests the execution of the self.initialize method when the INVOKE_EDIT event notification is triggered. The list view model will trigger this event when the user clicks on the one of grid’s edit buttons.
  • An update() method which utilizes an ajax post to send product updates to the server. On successful execution the method hides the panel and triggers the PRODUCT_UPDATED event notification.

ProductListVM

prodictListVM  is the view model that is bound to the product grid.

///////////////////////////////////////////////////////////////////
// ProductListVM

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

    // Properties
    self.products = ko.observableArray([]);

    self.columnDefs = [
        { field: 'productId', displayName: 'Id', width: 80 },
        { field: 'name', displayName: 'Name', width: 200 },
        { field: 'description', displayName: 'Description' },
        { field: 'productCategoryName', displayName: 'Product Category', width: 200 },
        { field: 'productId', displayName: ' ', cellTemplate: $('#editDeleteCellTemplate').html(), width: 150, sortable: false }
    ];

    self.filterOptions = {
        filterText: ko.observable(""),
        useExternalFilter: false
    };

    self.pagingOptions = {
        currentPage: ko.observable(1),
        pageSizes: ko.observableArray([2, 5, 10, 20, 50]),
        pageSize: ko.observable(2),
        totalServerItems: ko.observable(0)
    };

    self.sortInfo = ko.observable({ column: { 'field': 'name' }, direction: 'asc' });

    self.gridOptions = {
        data: self.products,
        columnDefs: self.columnDefs,
        autogenerateColumns: false,
        showGroupPanel: true,
        canSelectRows: false,
        showFilter: true,
        filterOptions: self.filterOptions,
        enablePaging: true,
        pagingOptions: self.pagingOptions,
        sortInfo: self.sortInfo,
        rowHeight: 35
    };

    // Subscriptions

    self.pagingOptions.pageSize.subscribe(function (data) {
        self.pagingOptions.currentPage(1);
        self.get();
    });

    self.pagingOptions.currentPage.subscribe(function (data) {
        self.get();
    });

    self.sortInfo.subscribe(function (data) {
        self.pagingOptions.currentPage(1);
        self.get();
    });

    notifier.subscribe(self.get, null, PRODUCT_UPDATED);

    // Methods

    self.get = function () {
        $loadingIndicator.show();

        $.ajax({
            url: productsUri,
            type: 'get',
            data: {
                'page': self.pagingOptions.currentPage(),
                'pageSize': self.pagingOptions.pageSize(),
                'filter': self.filterOptions.filterText == undefined ? '' : self.filterOptions.filterText(),
                'sort': self.sortInfo().column.field + ' ' + self.sortInfo().direction
            },
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                self.pagingOptions.totalServerItems(data.ProductCount);

                var productsArray = [];
                $.each(data.PageOfProducts, function (key, value) {
                    productsArray.push(
                        new product({
                            productId: value.ProductId,
                            name: value.Name,
                            description: value.Description,
                            productCategoryId: value.ProductCategoryId,
                            productCategoryName: value.ProductCategoryName
                        }));
                });
                self.products(productsArray);

                $loadingIndicator.hide();
            }
        });
    };

    self.add = function () {
        notifier.notifySubscribers(null, INVOKE_ADD);
    };

    self.edit = function (item) {
        notifier.notifySubscribers(item, INVOKE_EDIT);
    };

    self.delete = function (item) {

        bootbox.confirm("Are you sure?", function (result) {
            Example.show("Confirm result: " + result);
        });
        if (confirm("Are you sure you want to delete " + item.name() + "?")) {
            var dataObject = JSON.stringify({ id: item.productId() });

            $.ajax({
                url: productsUri + '/' + item.productId(),
                type: 'delete',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    self.get();
                }
            });
        }
    }
}

In addition to the functionality described in the previous blog post, productListVM is comprised of the following –

  • An additional column definition, which generates the column containing edit and delete buttons for each product. The column is generated based on a editDeleteCellTemplate column template. this template is outlined in the nest section.
  • A notifier subscription, registering the get() method to be called when the PRODUCT_UPDATED event is invoked. This event is invoked by either the add or edit view model when a product is updated. The grid is therefore refreshed in response to a product being updated.
  • An add() method, which invokes the INVOKE_ADD notification. This method is bound to the add buttons click event.
  • An edit() method, which invokes the INVOKE_EDIT notification. This method is bound to the grid’s edit buttons click event, and passes through the view model item specific to the button that was clicked.
  • A delete() method, which asked for conformation, and then uses an ajax delete call to delete the product. On successfull completion the get() method is called and hence the grid is refreshed.

Edit/Delete Cell Template

The following html template is used by the list view model to generate the column containing the edit and delete buttons –

<script type="text/template" id="editDeleteCellTemplate">
    <div>
        <button type="button" class="btn btn-primary btn-xs row-button" data-bind="click: function() { $parent.$userViewModel.edit($parent.entity); }">
            <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Edit
        </button>
        <button type="button" class="btn btn-danger btn-xs row-button" data-bind="click: function() { $parent.$userViewModel.delete($parent.entity); }">
            <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> Delete
        </button>
    </div>
</script>

Kicking it all off

First thing I do is create an instance of productListVM, and bind this instance to the list panel.

I then create an instance of productCategoryList, and call the get() method, which gets the product categories from the server.

I pass a callBack function to the productCategoryList.get() method, to ensure that the full list is retrieved prior to performing the following –

  • create a new instance of productAddVM, passing the product category list into the constructor, and binding this instance to the add panel.
  • create a new instance of productEditVM, passing the product category list into the constructor, and binding this instance to the edit panel.
  • and finally, call the prroductListVM.get() method to populate the product grid.
/////////////////////////////////////////////////////////////////
// Let's kick it all off

var productListVM = new productListVM();
ko.applyBindings(productListVM, $listPanel[0]);

var productCategoryList = new productCategoryList();

productCategoryList.get(function () {
    ko.applyBindings(new productAddVM(productCategoryList.productCategories()), $addPanel[0]);
    ko.applyBindings(new productEditVM(productCategoryList.productCategories()), $editPanel[0]);
    productListVM.get();
});

For completeness, here’s the full View Model code –

<script type="text/template" id="editDeleteCellTemplate">
<div>
    <button type="button" class="btn btn-primary btn-xs row-button" data-bind="click: function() { $parent.$userViewModel.edit($parent.entity); }">
        <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Edit
    </button>
    <button type="button" class="btn btn-danger btn-xs row-button" data-bind="click: function() { $parent.$userViewModel.delete($parent.entity); }">
        <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> Delete
    </button>
</div>
</script>

<script type="text/javascript">
$(function () {
    var $listPanel = $('#list-panel');
    var $addPanel = $('#add-panel');
    var $editPanel = $('#edit-panel');

    var $disablingDiv = $('#disabling-div');
    var $loadingIndicator = $('#loading-indicator');

    var productsUri = '/api/products';

    ///////////////////////////////////////////////////////////////////
    // Notifier
    var notifier = new ko.subscribable();
    var PRODUCT_UPDATED = "PRODUCT_UPDATED";
    var INVOKE_ADD = "INVOKE_ADD";
    var INVOKE_EDIT = "INVOKE_EDIT";

    ///////////////////////////////////////////////////////////////////
    // ProductCategory

    var productCategory = function (productCategoryId, name) {
        var self = this;

        // Properties
        self.productCategoryId = productCategoryId;
        self.name = name;
    }

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

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

        self.get = function (callBack) {
            $.ajax({
                url: '/api/productCategory',
                type: 'get',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    $.each(data, function (key, value) {
                        self.productCategories.push(new productCategory(value.ProductCategoryId, value.Name));
                    });

                    if (typeof callBack !== "undefined") {
                        callBack();
                    };
                }
            });
        }
    }

    ///////////////////////////////////////////////////////////////////
    // Product

    var product = function (data) {
        var self = this;

        self.productId = ko.observable(data.productId || 0);
        self.name = ko.observable(data.name || null);
        self.description = ko.observable(data.description || null);
        self.productCategoryId = ko.observable(data.productCategoryId || 0);
        self.productCategoryName = ko.observable(data.productCategoryName || null);
    }

    ///////////////////////////////////////////////////////////////////
    // ProductVM, ProductAddVM, and ProductEditVM

    var productVM = function (productCategories, panel) {
        var self = this;

        // Functional Inheritance

        ko.utils.extend(self, new product({}));

        // Properties

        self.productCategories = ko.observableArray(productCategories);

        // Validation

        self.name.extend({
            required: true,
            maxLength: 100
        });

        self.description.extend({
            required: true,
            maxLength: 1000
        });

        self.productCategoryId.extend({
            required: true
        });

        self.errors = ko.validation.group([self.productId, self.name, self.description, self.productCategoryId]);

        // State

        self.hasChanged = ko.observable(false);
        self.isSaving = ko.observable(false);

        self.isValid = ko.computed(function () {
            return self.errors().length == 0;
        });

        self.canSave = ko.computed(function () {
            return self.isValid() && self.hasChanged() && !self.isSaving();
        });

        // Subscriptions

        self.name.subscribe(function (value) {
            self.hasChanged(true);
        });

        self.description.subscribe(function (value) {
            self.hasChanged(true);
        });

        self.productCategoryId.subscribe(function (value) {
            self.hasChanged(true);
        });

        // Methods

        self.initialize = function (data) {
            if (data != null) {
                self.productId(data.productId() || 0);
                self.name(data.name() || null);
                self.description(data.description() || null);
                self.productCategoryId(data.productCategoryId() || 0);
            }
            else {
                self.errors.showAllMessages(false);
            }

            self.hasChanged(false);

            self.show();
        };

        self.cancel = function () {
            self.hide();
        };

        self.show = function () {
            transition.show(panel);
        }

        self.hide = function () {
            // Hide and tidy up
            transition.hide(panel, function () {
                self.productId(0);
                self.name(null);
                self.description(null);
                self.hasChanged(false);
                self.errors.showAllMessages(false);
            });
        }
    }

    var productAddVM = function (productCategories) {
        var self = this;

        var panel = $addPanel;

        // Functional Inheritance

        ko.utils.extend(self, new productVM(productCategories, panel));

        // Subscriptions

        notifier.subscribe(self.initialize, null, INVOKE_ADD);

        // Methods

        self.add = function () {

            if (self.errors().length == 0) {

                self.isSaving(true);

                var dataObject = ko.toJSON(this);

                $.ajax({
                    url: productsUri,
                    type: 'post',
                    data: dataObject,
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        self.isSaving(false);

                        self.hide();

                        notifier.notifySubscribers(null, PRODUCT_UPDATED);
                    }
                });
            }
            else {
                self.errors.showAllMessages();
            }
        };
    }

    var productEditVM = function (productCategories) {
        var self = this;

        var panel = $editPanel;

        // Functional Inheritance

        ko.utils.extend(self, new productVM(productCategories, panel));

        // Subscriptions

        notifier.subscribe(self.initialize, null, INVOKE_EDIT);

        // Methods

        self.update = function () {
            if (self.errors().length == 0) {

                self.isSaving(true);

                var dataObject = ko.toJSON(this);

                $.ajax({
                    url: productsUri,
                    type: 'put',
                    data: dataObject,
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        self.isSaving(false);

                        self.hide();

                        notifier.notifySubscribers(null, PRODUCT_UPDATED);
                    }
                });
            }
            else {
                self.errors.showAllMessages();
            }
        };
    }

    ///////////////////////////////////////////////////////////////////
    // ProductListVM

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

        // Properties
        self.products = ko.observableArray([]);

        self.columnDefs = [
            { field: 'productId', displayName: 'Id', width: 80 },
            { field: 'name', displayName: 'Name', width: 200 },
            { field: 'description', displayName: 'Description' },
            { field: 'productCategoryName', displayName: 'Product Category', width: 200 },
            { field: 'productId', displayName: ' ', cellTemplate: $('#editDeleteCellTemplate').html(), width: 150, sortable: false }
        ];

        self.filterOptions = {
            filterText: ko.observable(""),
            useExternalFilter: false
        };

        self.pagingOptions = {
            currentPage: ko.observable(1),
            pageSizes: ko.observableArray([2, 5, 10, 20, 50]),
            pageSize: ko.observable(2),
            totalServerItems: ko.observable(0)
        };

        self.sortInfo = ko.observable({ column: { 'field': 'name' }, direction: 'asc' });

        self.gridOptions = {
            data: self.products,
            columnDefs: self.columnDefs,
            autogenerateColumns: false,
            showGroupPanel: true,
            canSelectRows: false,
            showFilter: true,
            filterOptions: self.filterOptions,
            enablePaging: true,
            pagingOptions: self.pagingOptions,
            sortInfo: self.sortInfo,
            rowHeight: 35
        };

        // Subscriptions

        self.pagingOptions.pageSize.subscribe(function (data) {
            self.pagingOptions.currentPage(1);
            self.get();
        });

        self.pagingOptions.currentPage.subscribe(function (data) {
            self.get();
        });

        self.sortInfo.subscribe(function (data) {
            self.pagingOptions.currentPage(1);
            self.get();
        });

        notifier.subscribe(self.get, null, PRODUCT_UPDATED);

        // Methods

        self.get = function () {
            $loadingIndicator.show();

            $.ajax({
                url: productsUri,
                type: 'get',
                data: {
                    'page': self.pagingOptions.currentPage(),
                    'pageSize': self.pagingOptions.pageSize(),
                    'filter': self.filterOptions.filterText == undefined ? '' : self.filterOptions.filterText(),
                    'sort': self.sortInfo().column.field + ' ' + self.sortInfo().direction
                },
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    self.pagingOptions.totalServerItems(data.ProductCount);

                    var productsArray = [];
                    $.each(data.PageOfProducts, function (key, value) {
                        productsArray.push(
                            new product({
                                productId: value.ProductId,
                                name: value.Name,
                                description: value.Description,
                                productCategoryId: value.ProductCategoryId,
                                productCategoryName: value.ProductCategoryName
                            }));
                    });
                    self.products(productsArray);

                    $loadingIndicator.hide();
                }
            });
        };

        self.add = function () {
            notifier.notifySubscribers(null, INVOKE_ADD);
        };

        self.edit = function (item) {
            notifier.notifySubscribers(item, INVOKE_EDIT);
        };

        self.delete = function (item) {

            bootbox.confirm("Are you sure?", function (result) {
                Example.show("Confirm result: " + result);
            });
            if (confirm("Are you sure you want to delete " + item.name() + "?")) {
                var dataObject = JSON.stringify({ id: item.productId() });

                $.ajax({
                    url: productsUri + '/' + item.productId(),
                    type: 'delete',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        self.get();
                    }
                });
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // Transitions

    var transition = {

        duration: 200,

        show: function (target, callBack) {
            if (target.is(':hidden')) {
                $disablingDiv.show();
                target.slideDown(transition.duration, function () {
                    target.find('input[type!=hidden]:first').focus();
                    if (typeof callBack !== "undefined") {
                        callBack();
                    }
                });
            }
            else if (typeof callBack !== "undefined") {
                callBack();
            }
        },

        hide: function (target, callBack) {
            if (target.is(':visible')) {
                $disablingDiv.hide();
                target.slideUp(transition.duration, callBack);
            }
            else if (typeof callBack !== "undefined") {
                callBack();
            }
        }
    }

    /////////////////////////////////////////////////////////////////
    // Let's kick it all off

    var productListVM = new productListVM();
    ko.applyBindings(productListVM, $listPanel[0]);

    var productCategoryList = new productCategoryList();

    productCategoryList.get(function () {
        ko.applyBindings(new productAddVM(productCategoryList.productCategories()), $addPanel[0]);
        ko.applyBindings(new productEditVM(productCategoryList.productCategories()), $editPanel[0]);
        productListVM.get();
    });
});

</script>