Question

I have a jQuery DataTable configured for server-side processing against an ASP.NET MVC server.

To achieve progressive enhancement, an HTML table is rendered, and then upgraded to a DataTable. When the DataTable makes an AJAX call to retrieve more data, it expects elements of the returned JSON to correlate with the existing table-column layout.

This seems to cause some architectural friction, because:

During initial page rendering:

  • The Controller transforms database data into DTOs and establishes a ViewData model.
  • The ViewPage transforms the ViewData model into HTML with the help of HtmlHelper, etc.

Duriung AJAX updates:

  • The Controller transforms database data into table-cell data, with hyperlinks, etc.
  • The DataTable renders the returned data directly into the table cells.

The point here is that the Controller is now forced into knowing about the table rendering layout, when it's responsibility should be limited to passing back DTOs.

What's the correct pattern here? How do I support AJAX calls and adhere to the single-responsibility principal in the controller?


Some clarity:

My DTO has three properties:

public class AccountListing
{
    public int Id { get; set; }
    public string AccountCode { get; set; }
    public string AccountName { get; set; }
}

The rendered DataTable has four columns:

+--------------+--------------+------+------+
| Account Code | Account Name | View | Edit |
+--------------+--------------+------+------+
| 12345        | FooBar Inc.  | Link | Link |
+--------------+--------------+------+------+

The ViewPage renders the 3 property DTO into a 4 column table. If the Controller passes back the same 3 property DTO as AJAX JSON, the data table complains about missing columns... the data table expects the returned JSON to represent cell elements, as opposed to source data.

Currently I'm solving this using jQuery array transforms and custom table rendering, which effectively duplicates the logic of the ViewPage.

Is there any alternative?

Was it helpful?

Solution

Your current solution (doing the rendering on the client side) sound good to me.

The thing is, your DTOs do not have to correspond to what your view pages display. The popular pattern is having ViewModel objects for these situations.

For example :

public class AccountListingViewModel {
    public string AccountCode { get; set; }
    public string AccountName { get; set; }
    public string ViewLink { get; set; }
    public string EditLink { get; set; }
    public static AccountListingViewModel FromAccountListing(AccountListing o) {
        AccountListingViewModel returnObj = new AccountListingViewModel();
        //populate the properties from the parameter
        return returnObj;
    }
}

See [viewmodel], [model-view-viewmodel].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top