首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Telerik MVC AJAX绑定属性列上使用自定义日期格式化程序

在Telerik MVC AJAX绑定属性列上使用自定义日期格式化程序
EN

Stack Overflow用户
提问于 2012-02-08 18:05:53
回答 2查看 5.5K关注 0票数 4

我在我的ASP.NET MVC3应用程序上使用razor的最新版本的Telerik MVC控件。

我已经定义了我的网格结构如下:

代码语言:javascript
复制
@(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" })
)

我的视图模型如下所示:

代码语言:javascript
复制
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; }
}

我已经创建了一个日期格式化程序,我想在我的列中使用它来格式化日期:

代码语言:javascript
复制
public static class DateTimeExtensions
{
     public static string FormatDate(this DateTime instance)
     {
          return string.Format("{0:yyyy-MM-dd}", instance);
     }
}

如何在我的列中使用此format方法来格式化CreatedDate?我尝试了以下几种方法:

代码语言:javascript
复制
column.Bound(x => x.CreatedDate.FormatDate())
     .Title("Created")
     .Width(90);

..and我得到以下错误:

代码语言:javascript
复制
Bound columns require a field or property access expression.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-08 18:12:50

你必须绑定一个属性,所以你正在做的事情将不会起作用。您可以做的是:

代码语言:javascript
复制
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; }
}

然后

代码语言:javascript
复制
column.Bound(x => x.FormattedDate)
 .Title("Created")
 .Width(90);

(代码的语法不正确,因此您必须清理它:)

你也可以这样做

代码语言:javascript
复制
column.Bound(x => x.FormattedDate)
     .Title("Created")
     .Format("{0:MM/dd/yyyy hh:mm tt}")
     .Width(90);

如果我没记错的话

票数 9
EN

Stack Overflow用户

发布于 2012-02-08 18:11:21

您可以在GrantApplicationListViewModel类中设置日期的格式

代码语言:javascript
复制
public DateTime CreatedDate 
{
 get
 {
   return string.Format("{0:yyyy-MM-dd}", this);
 }
}

这对我很有效。或者您可以按照下面的方式使用

代码语言:javascript
复制
public DateTime CreatedDate 
    {
     get
     {
       return string.Format("{0:yyyy-MM-dd}", DateOfJoining);
     }    
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9191156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档