1
votes

I am having challenge making my Kendo Grid Title from an array columnName as shown in the code below. columnName is an array that i want to use as my column/field name.

@(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

1 Answers

2
votes

Thank you Prof. Pickle for your response.

This is what I have done. The method where the grid data is read from is as below.

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));
    }   

my model is

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; }

} 

Before the view comes up i pass in data to the grid if my session is not null else it passes nothing to the view as shown below:

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);
    }

I created a generic method that takes care of transforming my data to datatable by passing in the columns names and rows respectively without having to display every value for model properties. I want it to passing the field with values that are not "" or null. so that the grid displays it. My generic method is as follows:

//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;
    }

My Grid is now this

@(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 => events.Error("error_handler"))) )

If there any thing i need to explain, i will respond asap. Thank Prof. Pickle!