This is a migrated thread and some comments may be shown as answers.

Modify Grid in code-behind

2 Answers 188 Views
Grid
This is a migrated thread and some comments may be shown as answers.
2Trace
Top achievements
Rank 1
2Trace asked on 07 Apr 2013, 11:49 AM
Hi!

We just decided to upgrade our projects from Telerik grid to Kendo, but this has become a major issue for us, since we have a very deep integration. When we want to show a Grid, we use our own ViewHelper class. This class would modify a Telerik Grid to the way we like.

For instance Grids created this way could have a specific DataAnnotation on each of the models property, that specified:
  • Alternative columnname
  • If the column is hidden or not
  • Specific datetime format
  • Wheather or not to summarize this column
  • MANY other options
Also, there are many extensions to the Grid itself, like:
  • Should the grid have an Export button, for Excel export
  • Should the grid have vertical scrollbars
  • Should the grid have text areas over each column for filtering.
We hook on most of the Grids events, to run scrips before the ones provided in the ClientEvents setting.

We have hundreds of Grids created this way, and it makes it easy to maintain since all Grids are defined by their model. To do this, we created Grids like this in the View:
<%=ViewHelper.CreateGridFromType<OverviewTopFiveModel>(this)
                .Name("DailyTopFive")
                .DataBinding(dataBinding => dataBinding.Ajax()
                    .Select("AjaxDailyTopFive", "Home"))
                .Filterable()
                .Sortable()
                .ScrollBars(false)
%>
And CreateGridFromType would look like this:
public static GridBuilder<TModel> CreateGridFromType<TModel>(ViewPage page) where TModel : class
        {
            // create the custom grid
            var component = (page.ViewContext.HttpContext.Items[StyleSheetRegistrar.Key] as StyleSheetRegistrar) ?? new StyleSheetRegistrar(new WebAssetCollection(WebAssetDefaultSettings.StyleSheetFilesPath), page.ViewContext, DI.Current.Resolve<IWebAssetCollectionResolver>());
            var scriptWrapper = DI.Current.Resolve<ScriptWrapperBase>();
            var registrar2 = (page.ViewContext.HttpContext.Items[ScriptRegistrar.Key] as ScriptRegistrar) ?? new ScriptRegistrar(new WebAssetCollection(WebAssetDefaultSettings.ScriptFilesPath), new List<IScriptableComponent>(), page.ViewContext, DI.Current.Resolve<IWebAssetCollectionResolver>(), scriptWrapper);
            var test = new CustomViewComponentFactory(page.Html, DI.Current.Resolve<IClientSideObjectWriterFactory>(), ComponentBuilderBase<StyleSheetRegistrar, StyleSheetRegistrarBuilder>.Create(component), ComponentBuilderBase<ScriptRegistrar, ScriptRegistrarBuilder>.Create(registrar2));
            var cGrid = test.Grid<TModel>();
            var grid = new GridBuilder<TModel>(cGrid);
            // create the columns
            grid.Columns(CreateGridColumnsFromType(grid));
            // hook internal events
            grid.ClientEvents(e => e.OnLoad("onInternalGridLoad"));
            grid.ClientEvents(e => e.OnDataBinding("onInternalGridDataBinding"));
            grid.ClientEvents(e => e.OnDataBound("onInternalGridDataBound"));
            grid.ClientEvents(e => e.OnDetailViewExpand("onInternalGridDetailViewExpand"));
            grid.ClientEvents(e => e.OnDetailViewCollapse("onInternalGridDetailViewCollapse"));
            grid.ClientEvents(e => e.OnRowDataBound("onInternalRowDataBound"));
            grid.ClientEvents(e => e.OnCommand("onInternalGridCommand"));
            return grid;
        }

With the upgrade to Kendo, everything has changed. How on earth can we get a hold on the Grid in our ViewHelper? We need to preserve the settings made in the view, like the url to the DataSource and additional Columns. It is not good enough to just create a new Grid from scratch. It has to extend the Grid defined in the View. I hope you have some solution to our problem, since this way of creating Grids is crucial for us.

If i have not explained myself good enough, please let me know. Also, i can provide sample files - but i think the code provided explains most.

2 Answers, 1 is accepted

Sort by
0
Jayesh Goyani
Top achievements
Rank 2
answered on 08 Apr 2013, 05:12 AM
Hello,

 As per my experiance witn MVC, In MVC we can access control in controller.

We can achive your functionality in another way.

MODEL
namespace MvcApplication1.Models
{
    public class TestModels
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
        public int FID { get; set; }
    }
 
    public class SetPerssionOnPage
    {
        public bool showIDColumn { get; set; }
        public bool ShowAddButton { get; set; }
 
        public bool ShowUpdateButton { get; set; }
        public bool ShowDeleteButton { get; set; }
 
        public bool AllowScroll { get; set; }
    }
}


VIEW
@model MvcApplication1.Models.SetPerssionOnPage
...................
...................
<div>
    @(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ID).Visible(@Model.showIDColumn);
            columns.Bound(p => p.Name);
            columns.Template(@<text></text>).ClientTemplate(
                "# if ( \"true\" == \"" + @Model.ShowUpdateButton.ToString().ToLower() + "\") { #" +
                         "<a class='k-button k-button-icontext k-grid-edit' href='javascript: void(0)'><span class='k-icon k-iconSetImagePosition k-edit'></span>Edit</a>" +
                    "# } #" +
                     "# if ( \"true\" == \"" + @Model.ShowDeleteButton.ToString().ToLower() + "\") { #" +
                         "<a class='k-button k-button-icontext k-grid-delete'><span class='k-icon k-delete'></span>Delete</a>" +
                    "# } #").Title("Action").HeaderHtmlAttributes(new { @class = "fontbold" }).Width(200).Visible(@Model.ShowUpdateButton || @Model.ShowDeleteButton);
 
 
        })
        .Filterable()
        .Sortable()
                 .Scrollable(scrolling => scrolling.Enabled(@Model.AllowScroll).Height(500))
        .DataSource(dataSource => dataSource
            .Ajax()
 
                    .Read(read => read.Action("Grid_Read", "Home"))
             .Model(model => { model.Id(p => p.ID); })
        )
                        .ToolBar(toolbar => toolbar.Template(@Model.ShowAddButton ? "<a href='javascript: void(0)'  class='k-button k-button-icontext k-grid-add'><span class='k-icon k-add k-iconSetImagePosition'></span>Add New Item</a>" : string.Empty))
    )
</div>


CONTROLLER

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            SetPerssionOnPage model = new SetPerssionOnPage();
  
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            model.showIDColumn = false;
            model.ShowDeleteButton = false;
            model.ShowUpdateButton= true;
            model.AllowScroll = true;
            return View(model);
        }
  
        
  
        public ActionResult Grid_Read([DataSourceRequest] DataSourceRequest request)
        {
            List<TestModels> models = new List<TestModels>();
  
            for (int i = 1; i < 6; i++)
            {
  
                TestModels model = new TestModels();
                model.ID = i;
                model.Name = "Name" + i;
                models.Add(model);
  
            }
  
            return Json(models.ToDataSourceResult(request));
        }
    }




Thanks.
Jayehs Goyani
0
Accepted
2Trace
Top achievements
Rank 1
answered on 08 Apr 2013, 09:40 AM
Hi Jayesh

Thanks for your reply.

After reading and understanding the code i posted before, it was initially written by another teammember, i realize that it is extremely crippled.

Insted of sending the ViewPage pack and grab the grid from here i now use a different approach. I simply make a new HtmlHelperExtension and override the WidgetFactory. This allows me to manipulate with the Grid they way i want.

This should teach me to to read code better, before i make questions about it...
Tags
Grid
Asked by
2Trace
Top achievements
Rank 1
Answers by
Jayesh Goyani
Top achievements
Rank 2
2Trace
Top achievements
Rank 1
Share this question
or