Skip to content

Customising column rendering

Harry McIntyre edited this page Jul 26, 2016 · 1 revision

The IQueryable that is passed as the first parameter should be IQuerable where the properties correspond to the columns you want in the table, and the properties are of the rich Types (e.g. DateTime etc.) so that filters/sorts can be issued correctly.

The filters/sort/skip/take are applied to the IQueryable, and a page of results is generated. This is when we do a final transform to prettify any columns which need it.

The 3rd parameter, Func<TViewModel, object> transform is then run against each TViewModel in the page of results, and the properties from the transform result are merged over the properties from the TViewModel. This allows you to replace the column values with html or other values.


public class Message
{
    public DateTime CreatedDate{get;set;}
    public User User {get;set;} 
    public ICollection<Recipients> Recipients {get; set;}
    public string Text {get;set;}
}

public class MessageViewModel
{
    public DateTime CreatedDate{get;set;}
    public string User {get;set;} 
    [DataTablesExclude] public User UserEntity {get;set;} //dont want this as a column, we are keeping it here so we can use it in the transform  
    public string Text {get;set;}
}

[HttpPost]
ActionResult GetMessagesDataRows(DataTablesParam param)
{
    IQueryable<Message> messages = db.Query<Message>();
    IQueryable<MessageViewModel> messageViewModels = messages.Select(m => new MessageViewModel {
        CreatedDate = m.CreatedDate,
        User = m.User.Name,
        Text = m.Text
    });

    return DataTablesResult.Create(messages, param, x => new  {
        CreatedDate = x.CreatedDate.ToFriendlyTimeString(), 
        User =string.Format("<a href='/users/{0}'>{1}</a>", r.UserEnt.Id, r.UserEnt.Name)
    });
});


The transform would

  • render a friendly formatted CreatedDate
  • render a link for the User column
  • leave the Text column unchanged ( but still as a visible column)
Clone this wiki locally