Telerik网格自定义列构建/格式化

时间:2012-06-14 15:17:56

标签: c# asp.net-mvc telerik telerik-grid

我有一个带有动态数据源的telerik网格(网格最多可以使用大约10个完全不同的数据模型),因此我必须动态构建列(显然)。网格中的一列(具有某些模型)是表示以毫秒为单位的时间跨度的双精度。 我想要做的是将此双精度格式化为时间跨度 .Telerik代码如下所示:

<% Html.Telerik()
     .Grid(Model.DynamicGridDataSource)
     .Name("statisticalGrid")
     .Columns(a => GridHelper.GenerateColumns(a, Model.SelectedReport))
     .DataBinding(dataBinding => dataBinding.Ajax().Select("_SelectGrid", "Reports", new { reportId = Model.ReportId, dateFrom = Model.DateFrom, dateTo = Model.DateTo, date = Model.Date, AvailablePlans = Model.AvailablePlans }))
     .Sortable(GridSortSettingsBuilder => GridHelper.SortColumns(GridSortSettingsBuilder,
                                            Model.DynamicGridDataSource.GetType(),
                                            Model.SelectedReport))
     .Filterable()
     .Pageable(page => page.PageSize(25))
     .Reorderable(reorder => reorder.Columns(true))
     .Groupable
     (
         groupingSettingsBuilder => GridHelper.GroupColumns(groupingSettingsBuilder,
                                    Model.DynamicGridDataSource.GetType(),
                                    Model.SelectedReport)
     )
     .ClientEvents(events => events
          .OnColumnReorder("onReorder"))
     .Render();

和GridHelper.GenerateColumns看起来像这样:

public static void GenerateColumns(GridColumnFactory<dynamic> columnFactory, Company.Product.Data.Entity.Report reportStructure)
        {
            foreach (var columnLayout in reportStructure.ReportCols.OrderBy(o => o.ColumnSequence))
            {
                var columnBuilder = columnFactory.Bound(columnLayout.ColumnType);

                if (columnLayout.ColumnType.Equals("SessionLength") ||
                 columnLayout.ColumnType.Equals("AverageTime") ||
                 columnLayout.ColumnType.Equals("TotalTime") ||
                 columnLayout.ColumnType.Equals("CallTime"))
                {
                    // disable grouping
                    columnBuilder.Groupable(false);
                    string dataBindProperty = columnLayout.ColumnType;
                    if (columnLayout.DataFormat == "{0:T}")
                    {
                        //Even though the format looks like time ({0:T}), its actually a double which needs to be formatted here to look like a TimeSpan
                    }

                }

                if (!string.IsNullOrEmpty(columnLayout.Label))
                {
                    columnBuilder.Title(columnLayout.Label);
                }

                if (columnLayout.DataFormat != null && columnLayout.DataFormat == "{0:P}")
                {
                    columnBuilder.Format("{0:P}");
                }

                if (columnLayout.SumIndicator)
                {
                    if (columnLayout.DataFormat == "{0:T}")
                    {
                        AddAggregateToColumnTimeSpan(columnBuilder, Aggregate.Sum);
                    }
                    else
                    {
                        AddAggregateToColumn(columnBuilder, Aggregate.Sum);
                    }
                }

                if (columnLayout.HideIndicator)
                {
                    columnBuilder.Column.Hidden = true;
                }

            }
        }

我能够正确格式化页脚,但我不知道如何格式化列的其余部分,因为在telerik代码的上下文之外我无法访问item迭代器什么的有什么建议/想法吗?也许columnFactory.Bound(columnType).Format(/*something*/)

1 个答案:

答案 0 :(得分:1)

你说,“网格最多可以使用大约10种完全不同的模型”,所以也许不是试图在一个网格中代表所有这些模型,而是每个模型都有一个网格。您可以使用主机视图将每个网格放入其自己的局部视图中,使用某种机制来确定要加载的部分视图。这是一个简单的例子。

控制器

public ActionResult DynamicReport
{
    //Get your Model
    Model.model1 = model_01 = Model.DynamicGridDataSource.GetDynamicModel()
    //Get the name of what model is being returned so view knows which 
    //partial view to load
    ViewBag.Message = model_01.Name
    ...

    return View(model_01)
}

在视图中有一些条件逻辑来选择要加载的部分视图。

查看

<h2>View</h2>
@{
  string pView = "~/Views/Grid/Partial_01.cshtml";
  switch(ViewBag.Message)
  {
      case "p02":
      pView =  "~/Views/Grid/Parital_02.cshtml"
      break;
      .....
  }
}

@Html.Partial(pView)

PartialView_01

@model List<Models.Misc>
@(Html.Telerik().Grid(Model)
    .Name("Grid")
    .Columns(columns =>
    {
      columns.Bound(a => a.Id).Width(120);
      columns.Bound(a => a.Name).Width(100);
      columns.Bound(a => a.Value).Format("{0:#,##0.00}").Width(100).Title("Price");
    })
)

PartialView_02

@model List<Models.Temp>
@(Html.Telerik().Grid(Model)
  .Name("Grid")
  .Columns(columns =>
  {
    columns.Bound(o => o.Name)
            .Aggregate(aggregates => aggregates.Count())
            .FooterTemplate(@<text>Total Count: @item.Count</text>)
            .GroupFooterTemplate(@<text>Count: @item.Count</text>);

    columns.Bound(o => o.Start)
            .Template(@<text>@item.Start.ToShortDateString()</text>)
            .Aggregate(aggreages => aggreages.Max())
            .FooterTemplate(@<text>Max: @item.Max.Format("{0:d}")</text>)
            .GroupHeaderTemplate(@<text>Max: @item.Max.Format("{0:d}")</text>)
            .GroupFooterTemplate(@<text>Max: @item.Max.Format("{0:d}")</text>);

    columns.Bound(o => o.Value)
            .Width(200)
            .Aggregate(aggregates => aggregates.Average())
            .FooterTemplate(@<text>Average: @item.Average</text>)
            .GroupFooterTemplate(@<text>Average: @item.Average</text>);

    columns.Bound(o => o.tsMilliseconds)
          .Width(100)
          .Aggregate(aggregates => aggregates.Sum())
          .Template(@<text>@TimeSpan.FromMilliseconds(@item.tsMilliseconds)</text>)
          .Title("TimeSpan")
          .FooterTemplate(
          @<text>
                <div>Sum: @TimeSpan.FromMilliseconds(@Convert.ToDouble(@item.Sum.Value.ToString())) </div>
            </text>)
      //header if you group by TimeSpan
          .GroupHeaderTemplate(@<text>@item.Title: @item.Key (Sum: @TimeSpan.FromMilliseconds(@Convert.ToDouble(@item.Sum.Value.ToString())))</text>)
      //footer for grouping
          .GroupFooterTemplate(@<text>Sum: @TimeSpan.FromMilliseconds(@Convert.ToDouble(@item.Sum.Value.ToString()))</text>);
  })
    .Sortable()
    .Groupable(settings => settings.Groups(groups => groups.Add(o => o.Start)))
) 

等等,对于每个不同的模型。每个模型都有自己的局部视图,您可以轻松地格式化每个网格以适合其模型,同时仍然只有一个主视图。