Skip to content

Instantly share code, notes, and snippets.

@JoeGannon
Last active October 15, 2022 00:56
Show Gist options
  • Save JoeGannon/55966354dafcbf7b8d4cd53103723383 to your computer and use it in GitHub Desktop.
Save JoeGannon/55966354dafcbf7b8d4cd53103723383 to your computer and use it in GitHub Desktop.
namespace Grid.Web.Helpers.HtmlExtensions
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
public class Grid<TModel>
{
private IEnumerable<TModel> dataSource;
public List<TableColumn<TModel>> TableColumns = new List<TableColumn<TModel>>();
public Grid<TModel> Columns(Action<ColumnBuilder<TModel>> builder)
{
var columnBuilder = new ColumnBuilder<TModel>(this);
builder(columnBuilder);
return this;
}
public Grid<TModel> DataSource(IEnumerable<TModel> data)
{
dataSource = data;
return this;
}
public MvcHtmlString ToHtml()
{
foreach (var model in dataSource)
{
foreach (var column in TableColumns)
{
var value = column.GetValue(model);
var title = column.ColumnTitle;
var hidden = column.Hidden;
}
}
return new MvcHtmlString("");
}
}
public class ColumnBuilder<TModel>
{
private readonly Grid<TModel> _grid;
private TableColumn<TModel> tableColumn;
public ColumnBuilder(Grid<TModel> grid)
{
_grid = grid;
}
public ColumnBuilder<TModel> Bind<TProperty>(Expression<Func<TModel, TProperty>> expression)
{
var compiled = expression.Compile();
var _tableColumn = new TableColumn<TModel, TProperty>(compiled);
_grid.TableColumns.Add(_tableColumn);
tableColumn = _tableColumn;
return this;
}
public ColumnBuilder<TModel> Title(string title)
{
tableColumn.ColumnTitle = title;
return this;
}
public ColumnBuilder<TModel> Hide()
{
tableColumn.Hidden = true;
return this;
}
}
public class TableColumn<TModel, TProperty> : TableColumn<TModel>
{
public string ColumnTitle { get; set; }
public bool Hidden { get; set; }
public Func<TModel, TProperty> GetProperty { get; set; }
public TableColumn(Func<TModel, TProperty> getProperty)
{
GetProperty = getProperty;
}
public string GetValue(TModel model)
{
var result = GetProperty(model);
return result == null ? string.Empty : result.ToString();
}
}
public interface TableColumn<in TModel>
{
string ColumnTitle { get; set; }
bool Hidden { get; set; }
string GetValue(TModel model);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment