动态构建Kendo UI网格

时间:2013-03-08 10:29:19

标签: asp.net-mvc kendo-grid

我正在挑战从数组columnName创建我的Kendo Grid Title,如下面的代码所示。 columnName是一个我想用作列/字段名称的数组。

@(Html.Kendo()
    .Grid<rtxVending.Web.Models.ProductDetails>()
    .Name("ProductDetailGrid").ClientDetailTemplateId("")
    .HtmlAttributes(new { @style = "align:center; font-size:9px;" })
    .Columns(columns =>
    {
        var colums = rtxVending.Web.Repositories.SessionRepository.GetSessionObject<IList<rtxVending.Web.Models.
        ProductCategoryTags>>(ApplicationConstants.sesProductsHeaderCategoryTags);
        if (colums != null && colums.Count > 0)
        {
            **//columnName is an array that i want to use as my column/field name**
            var columnName = colums.Select(a => a.ValueX).ToArray();

            foreach (var column in columnName)
            {
                columns.Bound(column.ToString());
            }
        }
        else
        {
            columns.Bound(o => o.Amount).Width(100);
            columns.Bound(o => o.Value).Width(100);
            columns.Bound(o => o.Value1).Width(100);
            columns.Bound(o => o.Value2).Width(100);
            columns.Bound(o => o.Value3).Width(100);
            columns.Bound(o => o.Value4).Width(100);
            columns.Bound(o => o.Value5).Width(100);
            columns.Bound(o => o.Value6).Width(100);
            columns.Bound(o => o.Value7).Width(100);
            columns.Bound(o => o.Value8).Width(100);
            columns.Bound(o => o.Value9).Width(100);
            columns.Bound(o => o.Value10).Width(100);
        }
    })
    .Pageable(pager => pager.Refresh(true))
    .Sortable()
    .Scrollable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("GetProductDetailsGrid", "Products"))
        .Events(events => events.Error("error_handler"))
    )
)

1 个答案:

答案 0 :(得分:2)

谢谢Pickle教授的回复。

这就是我所做的。从中读取网格数据的方法如下。

public ActionResult GetProductDetailsGrid([DataSourceRequest] DataSourceRequest request)
    {
        try
        {
            List<ProductDetails> productDetails = null;
            //IEnumerable<ProductDetails> productDetails = null;

            if (SessionRepository.VerifySessionExists(ApplicationConstants.sesProductDetails))
            {
                productDetails = SessionRepository.GetSessionObject<List<ProductDetails>>(ApplicationConstants.sesProductDetails).ToList(); //.AsEnumerable();

                //Return converted list<T> as DataTable
                var dataTable = ToDataTable<ProductDetails>(productDetails);
                if (dataTable != null)
                {
                    var dataColumnCollection = dataTable.Columns;
                    SessionRepository.CacheSession<DataColumnCollection>(ApplicationConstants.sesAcquireStockDataColumnCollection, dataColumnCollection);
                }

                return Json(dataTable.ToDataSourceResult(request));
            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
            return Json(ModelState.ToDataSourceResult());
        }



        return Json(ModelState.ToDataSourceResult(request));
    }   

我的模特是

public class ProductDetails
{
        [Key,ScaffoldColumn(false)]
        public long ProductDetailId { get; set; }
        public int ProductHeaderId { get; set; }
        public double Amount { get; set; }
        public string Value { get; set; }
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
        public string Value4 { get; set; }
        public string Value5 { get; set; }
        public string Value6 { get; set; }
        public string Value7 { get; set; }
        public string Value8 { get; set; }
        public string Value9 { get; set; }
        public string Value10 { get; set; }
        public string Value1DisplayName {get; set;}
        public bool Valid { get; set; }

} 

在视图出现之前,如果我的会话不为null,则将数据传递给网格,否则它不会向视图传递任何内容,如下所示:

public ActionResult AcquireStock()
    {
        //TODO uncomment the Session Below 
        //SessionRepository.RemoveSession(ApplicationConstants.sesProductDetails); 

        var productHeader = new ProductHeaders();
        if (SessionRepository.VerifySessionExists(ApplicationConstants.sesProductDetails))
        {


            var productDetails = SessionRepository.GetSessionObject<List<ProductDetails>>(ApplicationConstants.sesProductDetails).ToList(); //.AsEnumerable();

            //Return converted list<T> as DataTable
            var dataTable = ToDataTable<ProductDetails>(productDetails);
            if (dataTable != null)
            {
                productHeader.ProductDetailsDataTable = dataTable;
                //SessionRepository.CacheSession<DataColumnCollection>(ApplicationConstants.sesAcquireStockDataColumnCollection, dataColumnCollection);
            }

            return View(productHeader);
        }

        productHeader.ProductDetailsDataTable = null;

        return View(productHeader);
    }

我创建了一个泛型方法,它通过分别传入列名和行来处理将数据转换为数据表,而不必显示模型属性的每个值。我希望它传递的字段的值不是“”或null。以便网格显示它。我的通用方法如下:

//Converts Generic List to DataTable
    private DataTable ToDataTable<T>(List<T> data)// T is any generic type
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
        int columnCount = 0;
        DataTable table = new DataTable();
        var colums = rtxVending.Web.Repositories.SessionRepository.GetSessionObject<IList<rtxVending.Web.Models.ProductCategoryTags>>(ApplicationConstants.sesProductsHeaderCategoryTags);
        if (colums != null && colums.Count > 0)
        {
            var columnName = colums.Select(a => a.ValueX).ToArray();

            for (int i = 0; i < columnName.Count(); i++)
            {
                table.Columns.Add(columnName[i]);
            }

            columnCount = columnName.Count();
        }
        else
        {
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }            
        }            

        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }

            object[] newValues = new object[columnCount];
            int j = 0;
            foreach (var p in values)
            {
                Type argType = p.GetType();

                if (argType == typeof(bool) && !((bool)p)) 
                {
                    newValues[j] = p;
                    j++;
                }
                else if(argType == typeof(int) && (int)p != 0)
                {
                    newValues[j] = p;
                    j++;
                }
                else if (argType == typeof(double) && (double)p != 0)
                {
                    newValues[j] = p;
                    j++;
                }
                else if (argType == typeof(string) && p != null && p != string.Empty)
                {
                    newValues[j] = p;
                    j++;
                }

                if (j >= columnCount)
                    break;
            }

            //table.Rows.Add(values);
            //table.Rows.Add(newValues);
        }
        return table;
    }

我的网格现在是

@(Html.Kendo()
        //.Grid<rtxVending.Web.Models.ProductDetails>()
                  .Grid(Model.ProductDetailsDataTable)
                  .Name("ProductDetailGrid")//.ClientDetailTemplateId("")
                  .HtmlAttributes(new { @style = "align:center; font-size:9px;" })
                  .Columns(columns =>
                  {
                      //var columnData = rtxVending.Web.Repositories.SessionRepository.GetSessionObject<System.Data.DataColumnCollection>(ApplicationConstants.sesAcquireStockDataColumnCollection);

                      //if(columnData != null && columnData.Count > 0)
                      if (Model.ProductDetailsDataTable != null)
                      foreach (System.Data.DataColumn column in Model.ProductDetailsDataTable.Columns)
                      {
                          columns.Bound(column.ColumnName);
                      }
})
.Pageable(pager => pager.Refresh(true))   
.Sortable()
.Scrollable()    
.DataSource(dataSource => dataSource
    .Ajax()
    .Read(read => read.Action("GetProductDetailsGrid", "Products"))
                      .Model(model =>
                    {
                        if (Model.ProductDetailsDataTable != null)
                        foreach (System.Data.DataColumn column in Model.ProductDetailsDataTable.Columns)
                        {
                            model.Field(column.ColumnName, column.DataType);
                        }                
                    })

.Events(events =&gt; events.Error(“error_handler”))) )

如果有任何我需要解释的事情,我会尽快回复。谢谢Pickle教授!