Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom date formatter on a Telerik MVC AJAX bound property column

I am using the latest version of Telerik MVC controls on my ASP.NET MVC3 app with razor.

I have defined my grid structure as follows:

@(Html.Telerik()
     .Grid<GrantApplicationListViewModel>()
     .Name("grdGrantApplications")
     .Columns(column =>
     {
          column.Bound(x => x.FullName)
               .Title("Owner")
               .Width(200);

          column.Bound(x => x.CreatedDate)
               .Title("Created")
               .Width(90);
     })
     .DataBinding(dataBinding => dataBinding.Ajax().Select("AjaxGrantApplicationsBinding", "Home"))
     .Pageable(paging => paging.PageSize(30))
     .TableHtmlAttributes(new { @class = "telerik-grid" })
)

My view model looks like:

public class GrantApplicationListViewModel
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
          get { return FirstName + " " + LastName; }
     }

     public DateTime CreatedDate { get; set; }
}

I have created a date formatter that I would like to use in my column to format the date:

public static class DateTimeExtensions
{
     public static string FormatDate(this DateTime instance)
     {
          return string.Format("{0:yyyy-MM-dd}", instance);
     }
}

How would I use this format method in my column to format CreatedDate? I tried the following:

column.Bound(x => x.CreatedDate.FormatDate())
     .Title("Created")
     .Width(90);

..and I get the following error:

Bound columns require a field or property access expression.
like image 750
Brendan Vogt Avatar asked Dec 21 '22 02:12

Brendan Vogt


1 Answers

you have to bind to a property, so what you are doing will not work. What you CAN do is:

public class GrantApplicationListViewModel
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
          get { return FirstName + " " + LastName; }
     }

     public DateTime CreatedDate { get; set; }
     public DateTime FormattedDate{ get{ return FormatDate(CreatedDate)}; set; }
}

And then

column.Bound(x => x.FormattedDate)
 .Title("Created")
 .Width(90);

(The code is not syntax correct so you have to clean it up :))

you could also do

column.Bound(x => x.FormattedDate)
     .Title("Created")
     .Format("{0:MM/dd/yyyy hh:mm tt}")
     .Width(90);

If I am not mistaken

like image 147
Nealv Avatar answered Dec 24 '22 01:12

Nealv