格式化webgrid中的日期时间和小数 [英] Format datetime and decimal in a webgrid

查看:94
本文介绍了格式化webgrid中的日期时间和小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自模式的数据填充MVC WebGrid,该模式在设计时是未知的。虽然我正在努力格式化数据,但一切正常。我只是不知道设置类型为Func< object,object>的属性的语法。



在控制器中

I'm populating an MVC WebGrid with data from a schema which is unknown at design time. It's all working fine, although I'm struggling with formatting the data. I just don't know the syntax to set a property of type Func<object, object>.

In the controller

var fields = GetListOfFieldsFromDB();
foreach (var f in fields)
{
    var c = new System.Web.Helpers.WebGridColumn();
    c.ColumnName = f.FieldName;
    c.Header = f.FieldAlias;
    c.CanSort = true;
    switch (f.SqlDataType)
    {
        case "datetime":
            c.Format = (item) => string.Format("{0:dd MMM yyyy}", 
                             item.DontKnowTheNameOfTheFieldYet; // Need help here . 
            break;

        case "decimal":
            c.Format = item => item.ToString("C"); // Need more help here. 
                                                   // No clue what the syntax should be.
            break;

         // some more formats here
         ...
     }

   columnList.Add(c);
}





在视图中



In the view

var grid = new WebGrid(source: Model.Records, canPage: true, rowsPerPage: 20);
@grid.GetHtml(tableStyle: "table", columns: Model.Columns)





我尝试过:





What I have tried:

c.Format = item => item.ToString("C"); //doesn't work

推荐答案

尝试使用索引器:

Try using the indexer:
switch (f.SqlDataType)
{
    case "datetime":
        c.Format = item => string.Format("{0:dd MMM yyyy}", item[f.FieldName]);
        break;
    
    case "decimal":
        c.Format = item => item[f.FieldName].ToString("C");
        break;
 
    ...
}


这篇关于格式化webgrid中的日期时间和小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆