public IrisGridBuilder(HtmlHelper helper) { Type modelType = typeof(T); IrisGridAttribute gridAttribute = modelType.GetCustomAttribute <IrisGridAttribute>(); if (gridAttribute == null) { throw new InvalidOperationException("You cannot create a grid control with an object that does not have the IrisGridAttribute."); } DatabaseModelBindings bindings = modelType.GetDatabaseBindings(); PropertyInfo[] modelProperties = modelType.GetProperties(); AjaxDataSourceBuilder <T> dataSourceBuilder = null; UserService userService = new UserService(); using (SecurityUserService securityUserService = new SecurityUserService()) { WidgetFactory factory = new WidgetFactory(helper); builder = factory.Grid <T>(); builder.DataSource(ds => { dataSourceBuilder = ds.Ajax(); // .Aggregates(a => // { // a.Add(p => p.Labor_Quantity).Sum(); // a.Add(p => p.Equipment_Quantity).Sum(); // a.Add(p => p.Material_Quantity).Sum(); // a.Add(p => p.OutSideService_Quantity).Sum(); // }) //dataSourceBuilder.Events(e => //{ // e.Error("error"); // e.Change("onChange"); //}); dataSourceBuilder.PageSize(100); dataSourceBuilder.ServerOperation(true); dataSourceBuilder.Read(r => r.Url(GetAbsoluteUrl(gridAttribute.ReadPath)).Type(HttpVerbs.Get)); dataSourceBuilder.Create(c => c.Url(GetAbsoluteUrl(gridAttribute.CreatePath)).Type(HttpVerbs.Post)); dataSourceBuilder.Update(u => u.Url(GetAbsoluteUrl(gridAttribute.UpdatePath)).Type(HttpVerbs.Post)); dataSourceBuilder.Destroy(d => d.Url(GetAbsoluteUrl(gridAttribute.DestroyPath)).Type(HttpVerbs.Post)); }); builder.Name("grid"); builder.Columns(c => { // Create our command column for this object c.Command(command => { command.Destroy(); command.Edit(); }).Lockable(true).Locked(false).Width(180).Visible(userService.ValidateSecurityLevel(bindings.TableName, 3)); //.Model(model => // { // model.Id(m => m.Timecard_Key); // model.Field(m => m.Equipment_Unit_Cost).Editable(true); // model.Field(m => m.FuelImport).Editable(false); // model.Field(m => m.DateStamp).Editable(false); // model.Field(m => m.SecurityUser_Key).Editable(false); // model.Field(m => m.Timecard_Key).DefaultValue("1600000000"); // model.Field(m => m.SecurityUser_Key).DefaultValue(ViewData["CurrentSecurityUser"]); // model.Field(m => m.CreatedBySecurityUser_Key).DefaultValue(ViewData["CurrentSecurityUser"]); // model.Field(m => m.DateStamp).DefaultValue(DateTime.Now); // }) dataSourceBuilder.Aggregates(a => { dataSourceBuilder.Model(model => { // Setup the columns from our model properties foreach (PropertyInfo p in modelProperties) { // Get our column settings from the property attribute or use a default one IrisGridColumnAttribute columnAttributes = p.GetCustomAttribute <IrisGridColumnAttribute>(); if (columnAttributes == null) { columnAttributes = IrisGridColumnAttribute.Default; } switch (columnAttributes.Aggregate) { case AggregateMode.Sum: a.Add(p.Name, p.PropertyType).Sum(); break; case AggregateMode.Min: a.Add(p.Name, p.PropertyType).Min(); break; case AggregateMode.Max: a.Add(p.Name, p.PropertyType).Max(); break; case AggregateMode.Average: a.Add(p.Name, p.PropertyType).Average(); break; } if (p.Name == bindings.KeyFieldName) { model.Id(p.Name); } else { DataSourceModelFieldDescriptorBuilder <object> fieldBuilder = model.Field(p.Name, p.PropertyType); if (p.Name.EndsWith("User_Key", StringComparison.InvariantCultureIgnoreCase)) { fieldBuilder.DefaultValue(securityUserService.CurrentSecurityUser()); } } GridBoundColumnBuilder <T> column = c.Bound(p.Name); column.Lockable(true).Locked(false); // Setup our formatting for this column if (string.IsNullOrEmpty(columnAttributes.Format) == false) { column.Format(columnAttributes.Format); } // Setup our custom editor templates if they are needed if (p.PropertyType == typeDate) { column.EditorTemplateName("IRISDate"); } // Setup custom attributes if (p.GetCustomAttribute <RequiredAttribute>() != null) { column.HeaderHtmlAttributes(new { @Class = "required-field" }); } column.Width(columnAttributes.Width); } }); }); }); // Setup our column menus for filtering and sorting builder.ColumnMenu(m => { m.Enabled(true); m.Filterable(true); m.Sortable(true); m.Columns(true); }); // Setup our editable configuration builder.Editable(e => { e.Mode(GridEditMode.InLine); e.CreateAt(GridInsertRowPosition.Top); e.DisplayDeleteConfirmation(false); }); builder.Events(e => { // e.Edit("onGridEdit"); // e.Save("ValidateRow"); // Used for Update button // e.SaveChanges("ValidateRow"); // Used for Alt + s // e.DataBound("SelectFirstRow"); }); //.Excel(excel => excel // .FileName("Timecard.xlsx") // .Filterable(true) // .ProxyURL(Url.Action("Excel_Export_Save", "Grid")) //) //.Pdf(pdf => pdf // .FileName("Timecard.pdf") // .ProxyURL(Url.Action("Pdf_Export_Save", "Grid")) // .AllPages() //) builder.Filterable(); builder.Navigatable(setting => setting.Enabled(true)); builder.Pageable(p => p.Refresh(true).PageSizes(true).ButtonCount(5)); builder.Scrollable(a => a.Height(500)); builder.Resizable(resize => resize.Columns(true)); builder.Reorderable(reorder => reorder.Columns(true)); builder.Sortable(); builder.Selectable(); //.ToolBar(toolBar => //{ // toolBar.Create(); // toolBar.Excel(); // toolBar.Pdf(); //}) //.DataSource(ds => ds // .Ajax() // // .Sort(s => s.Add(t => t.Task_Date)) //.Columns(c => //{ // c.Command(command => { command.Destroy(); command.Edit(); }).Lockable(true).Locked(false).Width(180).Visible(AuthHelper.ValidateSecurityLevel("Timecard", 3)); // c.Bound(p => p.Task_Date).Width(180).Lockable(true).Locked(false).EditorTemplateName("IRISDate").HeaderHtmlAttributes(new { @Class = "required-field" }); // c.ForeignKey(p => p.Activity_Key, (System.Collections.IEnumerable)ViewData["Activities"], "Field1", "Field2").Width(350).Lockable(true).HeaderHtmlAttributes(new { @Class = "required-field" }).EditorTemplateName("IRISGridForeignKeyWithFilter"); // c.ForeignKey(p => p.Project_Key, (System.Collections.IEnumerable)ViewData["Projects"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.ProjectSub_Key, (System.Collections.IEnumerable)ViewData["ProjectSubs"], "ProjectSub_Key", "NameDesc").EditorTemplateName("ProjectSub").Width(200); // c.Bound(p => p.Crew_Num).Width(120); // c.ForeignKey(p => p.Employee_Key, (System.Collections.IEnumerable)ViewData["Employees"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.Labor_Quantity).HtmlAttributes(new { style = "text-align: right" }).Width(150).ClientGroupFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#").ClientFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#"); // c.ForeignKey(p => p.Pay_Type_Key, (System.Collections.IEnumerable)ViewData["Pay_Types"], "Field1", "Field2").Width(150).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.Premium_Key, (System.Collections.IEnumerable)ViewData["Premiums"], "Field1", "Field2").Width(150).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.Override_Labor_Rate).Format("{0:c}").HtmlAttributes(new { style = "text-align: right" }).Width(200); // c.Bound(p => p.Production).HtmlAttributes(new { style = "text-align: right" }).Width(130).ClientGroupFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#").ClientFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#"); // c.Bound(p => p.Equipment_Quantity).HtmlAttributes(new { style = "text-align: right" }).Width(200).ClientGroupFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#").ClientFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#"); // c.ForeignKey(p => p.Equipment_Key, (System.Collections.IEnumerable)ViewData["Equipments"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.Equipment_Unit_Cost).Format("{0:c}").HtmlAttributes(new { style = "text-align: right" }).Width(120); // c.Bound(p => p.Material_Quantity).HtmlAttributes(new { style = "text-align: right" }).Width(120).ClientGroupFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#").ClientFooterTemplate("Sum: #= kendo.format('{0:n}', sum)#"); // c.ForeignKey(p => p.Inventory_Location_Key, (System.Collections.IEnumerable)ViewData["Inventory_Locations"], "Inventory_Location_Key", "NameDesc").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.UOMName).Width(100); // c.Bound(p => p.Material_Description).Width(120); // c.Bound(p => p.Material_Unit_Cost).Format("{0:c}").HtmlAttributes(new { style = "text-align: right" }).Width(150); // c.ForeignKey(p => p.ResourceClass_Key, (System.Collections.IEnumerable)ViewData["ResourceClasss"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.OutSideServiceDescription).Width(120); // c.Bound(p => p.OutSideService_Quantity).HtmlAttributes(new { style = "text-align: right" }).Width(100); // c.Bound(p => p.OutSideServiceCost).Format("{0:c}").HtmlAttributes(new { style = "text-align: right" }).Width(120); // c.ForeignKey(p => p.Mgt_Unit_Key, (System.Collections.IEnumerable)ViewData["Mgt_Units"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.Program_Key, (System.Collections.IEnumerable)ViewData["Programs"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.Zone_Key, (System.Collections.IEnumerable)ViewData["Zones"], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.RBF_Key, (System.Collections.IEnumerable)ViewData["RBFs"], "Field1", "Field2").Width(200).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.Road_Key, (System.Collections.IEnumerable)ViewData["Roads"], "Field1", "Field2").Width(200).EditorTemplateName("IRISGridForeignKey"); // c.ForeignKey(p => p.RoadName_Key, (System.Collections.IEnumerable)ViewData["RoadNames"], "Field1", "Field2").Width(200).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.Beg_Point).Width(120); // c.Bound(p => p.End_Point).Width(120); // c.Bound(p => p.FromLocation).Width(180); // c.Bound(p => p.ToLocation).Width(180); // c.ForeignKey(p => p.Reason_Key, (System.Collections.IEnumerable)ViewData["Reasons"], "Field1", "Field2").Width(200).EditorTemplateName("IRISGridForeignKey"); // c.Bound(p => p.Comments).Width(280); // c.Bound(p => p.EquipmentMiles).HtmlAttributes(new { style = "text-align: right" }).Width(250); // c.Bound(p => p.EquipmentHours).HtmlAttributes(new { style = "text-align: right" }).Width(250); // // User defined fields // string title; // string userType; // //ViewBag.UserDefinedFields.User1 // for (int i = 0; i < ViewBag.UserDefinedFields.Count; i++ ) // { // title = ViewBag.UserDefinedFields[i].Title; // userType = ViewBag.UserDefinedFields[i].Type; // switch (userType) // { // case "String": // c.Bound(ViewBag.UserDefinedFields[i].Field).Title(title).Width(120); // break; // case "Date": // c.Bound(ViewBag.UserDefinedFields[i].Field).Title(title).EditorTemplateName("Date").Width(150); // break; // case "Numeric": // c.Bound(ViewBag.UserDefinedFields[i].Field).Title(title).EditorTemplateName("Number").HtmlAttributes(new { style = "text-align: right" }).Width(120); // break; // case "Checkbox": // c.Bound(ViewBag.UserDefinedFields[i].Field).Title(title).HtmlAttributes(new { style = "text-align: center" }).ClientTemplate("<input type='checkbox' #=" + ViewBag.UserDefinedFields[i].Field + " ? checked='checked' : '' # class='chkbx' disabled='disabled'></input>").Width(120); // break; // case "Lookup": // c.ForeignKey(ViewBag.UserDefinedFields[i].Field, (System.Collections.IEnumerable)ViewData["LookupUser" + (i + 1).ToString()], "Field1", "Field2").Width(350).EditorTemplateName("IRISGridForeignKey"); // break; // } // } // c.Bound(p => p.FuelImport).HtmlAttributes(new { style = "text-align: center" }).ClientTemplate("<input type='checkbox' #=FuelImport ? checked='checked' : '' # class='chkbx' disabled='disabled' readonly='readonly'></input>").Width(200); // c.Bound(p => p.Error_Message).Width(220); // c.Bound(p => p.DateStamp).Format("{0: MM/d/yyyy hh:mm:ss}").Width(175); // c.ForeignKey(p => p.SecurityUser_Key, (System.Collections.IEnumerable)ViewData["SecurityUsers"], "SecurityUser_Key", "UserName").Width(140); //}) //) } }
public static GridBuilder <T> VnrGrid <T>(this HtmlHelper helper, GridBuilderInfo builderInfo) where T : class { #region PageableBuilder Action <PageableBuilder> pageable = new Action <PageableBuilder>(d => d.PageSizes(builderInfo.ShowPageSize).Input(builderInfo.ShowInputPageNumber).PreviousNext(builderInfo.ShowNextPrevious).Numeric(builderInfo.ShowPageNumber).Refresh(true).ButtonCount(5)); builderInfo.ObjectType = builderInfo.ObjectType != null ? builderInfo.ObjectType : typeof(T); Action <GridSelectionSettingsBuilder> selection = new Action <GridSelectionSettingsBuilder>(d => d.Mode(builderInfo.SelectionMode).Type(builderInfo.SelectionType)); Action <GridToolBarCommandFactory <T> > toolBar = new Action <GridToolBarCommandFactory <T> >(d => { if (builderInfo.ShowCreateButton && !string.IsNullOrWhiteSpace(builderInfo.CreateActionUrl)) { d.Create().Text(DefaultConstants.Create.TranslateString()); } if (builderInfo.ShowSaveButton && !string.IsNullOrWhiteSpace(builderInfo.EditActionUrl)) { d.Save().Text(DefaultConstants.Create.TranslateString()); } if (builderInfo.ShowCustomCreate && !string.IsNullOrWhiteSpace(builderInfo.EventCustomAdd)) { d.Custom().Text(DefaultConstants.Create.TranslateString()).Url("#").HtmlAttributes(new { onclick = builderInfo.EventCustomAdd }); } if (builderInfo.ShowCustomSaveChanges && !string.IsNullOrWhiteSpace(builderInfo.EventCustomSaveChanges) && !string.IsNullOrWhiteSpace(builderInfo.EventCustomCancelChanges)) { d.Custom().Text(builderInfo.CustomSaveChangesText).Url("#").HtmlAttributes(new { onclick = builderInfo.EventCustomSaveChanges }); d.Custom().Text(builderInfo.CustomCancelChangesText).Url("#").HtmlAttributes(new { onclick = builderInfo.EventCustomCancelChanges }); } }); Action <GridEditingSettingsBuilder <T> > editing = new Action <GridEditingSettingsBuilder <T> >(d => { d.Mode(builderInfo.EditMode); if (!string.IsNullOrWhiteSpace(builderInfo.EditTemplate)) { d.TemplateName(builderInfo.EditTemplate); } }); Action <GridEventBuilder> events = new Action <GridEventBuilder>(d => { //if (builderInfo.ForeignKey.Count>0) // d.Save("onSave"); if (!string.IsNullOrWhiteSpace(builderInfo.SelectionHandler)) { d.Change(builderInfo.SelectionHandler); } if (!string.IsNullOrWhiteSpace(builderInfo.EventSaveChanges)) { d.SaveChanges(builderInfo.EventSaveChanges); } if (!string.IsNullOrWhiteSpace(builderInfo.EventDataBound)) { d.DataBound(builderInfo.EventDataBound); } else { //[Tung.Ly 20140908 ] : dùng mặc định (viết ở _layout.cshtml ở main) d.DataBound("dataBound"); } if (!string.IsNullOrWhiteSpace(builderInfo.EvenEdit)) { d.Edit(builderInfo.EvenEdit); } }); #endregion #region GridColumnFactory var lockedCol = false; if (builderInfo.LockedFields != null && builderInfo.LockedFields.Any()) { lockedCol = true; } Action <GridColumnFactory <T> > columns = new Action <GridColumnFactory <T> >(column => { if (builderInfo.ValueFields != null) { column.AutoGenerate(builderInfo.ValueFields.Count() == 0); if (builderInfo.ShowCheckbox) { if (builderInfo.ShowCheckAll) { column.Bound("").Title("").HeaderTemplate("<input type='checkbox' id='mastercheckbox' /><div style='border: solid 1px #c5c5c5; margin-top: -3px; border-radius: initial; display: none; width: 60px; position: fixed; z-index: 99; background-color: #F8F8F8; ' class='hrm_treeview' id='MultipleSelectForPage'> <label><input type='radio' value='0' name='selectOnePageOrAllPage' checked /> Page</label><br /> <label><input value='1' type='radio' name='selectOnePageOrAllPage' /> All</label></div>").ClientTemplate("<input type='checkbox' value='#=ID#' class='checkboxGroups'/>").Width(25).Locked(lockedCol).Sortable(false); } else { column.Bound("").Title("").ClientTemplate("<input type='checkbox' value='#=ID#' class='checkboxGroups'/>").Width(25).Locked(lockedCol).Sortable(false); } } if (builderInfo.ShowEditIcon) { column.Bound("").Title("").ClientTemplate("<img src='/Content/images/icons/edit-file-icon.png' title='Edit' alt='Edit' name='gridEditImgButton' class='gridEditImgButton' />").Width(30).Locked(lockedCol).Sortable(false); } if (builderInfo.ShowCommand) { column.Command(d => { if (builderInfo.ShowEditButton && !string.IsNullOrWhiteSpace(builderInfo.EditActionUrl)) { d.Edit() .Text(string.Empty) .UpdateText(DefaultConstants.Save.TranslateString()) .CancelText(string.Empty); // d.Edit().HtmlAttributes(new{@class="abdd"}) } if (builderInfo.ShowDeleteButton && !string.IsNullOrWhiteSpace(builderInfo.DeleteActionUrl)) { d.Destroy().Text(DefaultConstants.Delete.TranslateString()); } if (builderInfo.ShowCustomEdit && !string.IsNullOrWhiteSpace(builderInfo.EventCustomEdit)) { d.Custom(builderInfo.EditText).HtmlAttributes(new { @class = "k-icon k-i-pencil" }).Click(builderInfo.EventCustomEdit); } }).Width(170); } foreach (var valueField in builderInfo.ValueFields) { var locked = false; if (builderInfo.LockedFields != null) { if (builderInfo.LockedFields.Contains(valueField)) { locked = true; } } GridBoundColumnBuilder <T> bound = null; string displayField = string.Empty, formatField = string.Empty, hyperlinkField = string.Empty, template = string.Empty; bool filterable = false; Type fieldValueType = GetFieldValueType(builderInfo, valueField); if (fieldValueType != null) { //Biến phân biệt đã add foreignKey hay chưa bool _tmp = false; foreach (var foreignKey in builderInfo.ForeignKey) { if (foreignKey.Key.ToString() == valueField) { if (foreignKey.Key != null && foreignKey.Value != null && foreignKey.Value.Count() > 3) { IList lstFk = (IList)foreignKey.Value[2]; if (lstFk != null) { if (foreignKey.Value[4].ToString() != string.Empty) { bound = column.ForeignKey(foreignKey.Key.ToString(), lstFk, foreignKey.Value[0].ToString(), foreignKey.Value[1].ToString()).Width(150).Title(foreignKey.Value[3].ToString().TranslateString()).EditorTemplateName(foreignKey.Value[4].ToString()); } else { bound = column.ForeignKey(foreignKey.Key.ToString(), lstFk, foreignKey.Value[0].ToString(), foreignKey.Value[1].ToString()).Width(150).Title(foreignKey.Value[3].ToString().TranslateString()); } } _tmp = true; break; } } } if (!_tmp) { bound = column.Bound(fieldValueType, valueField).Locked(locked); if (fieldValueType.IsBoolean()) { bound.ClientTemplate("<input type='checkbox' disabled='" + builderInfo.DisabledCheckbox + "' #= " + valueField + " ? 'checked=checked':'' # class='chkbx' />"); } else if (fieldValueType.IsDateTime() || fieldValueType.IsFloat() || fieldValueType.IsNumeric() || fieldValueType.IsDouble() || fieldValueType.IsInteger() || fieldValueType.IsDecimal()) { bound.HtmlAttributes(new { style = "text-align:right" }); } if (fieldValueType.IsDouble()) { bound.EditorTemplateName("Number"); } if (fieldValueType.IsFloat()) { bound.EditorTemplateName("Percent"); } } } else { bound = column.Bound(valueField).Locked(locked); } if (builderInfo.HasDisplayFields()) { displayField = builderInfo.DisplayFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); } if (string.IsNullOrWhiteSpace(displayField)) { displayField = valueField; } bound.Title(displayField.TranslateString()); #region Format Column if (builderInfo.HasFormatFields()) { formatField = builderInfo.FormatFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); } if (builderInfo.HasHyperlink()) { hyperlinkField = builderInfo.HyperlinkFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); } if (builderInfo.HasFilterable()) { filterable = builderInfo.Filterable.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); } //bound.Filterable(filterable); bound.Filterable(filterable).Filterable(_filterable => _filterable .Extra(false) .Operators(ops => ops.ForString(str => str.Clear() .Contains("Contains") .StartsWith("Starts with") .EndsWith("Ends with") .IsEqualTo("Is equal to")) )); if (builderInfo.HasTemplate()) { template = builderInfo.Template.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); } if (builderInfo.HasSizeFields()) { int fieldWidth = builderInfo.SizeFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); if (fieldWidth >= 10) { bound.Width(fieldWidth); } } if (string.IsNullOrWhiteSpace(formatField)) { formatField = GetDefaultFormat(fieldValueType); } if (!string.IsNullOrWhiteSpace(hyperlinkField)) { var itemHyperlink = hyperlinkField.Split(','); if (itemHyperlink.Count() > 1) { bound.ClientTemplate("<a onClick=\"" + itemHyperlink[0] + "('#=" + itemHyperlink[1] + "#')\">#=" + valueField + "#</a>"); } else { bound.ClientTemplate("<a onClick=\"" + hyperlinkField + "('#=ID#')\">#=" + valueField + "#</a>"); } } if (builderInfo.SumFields != null && builderInfo.SumFields.Any()) { foreach (var field in builderInfo.SumFields) { if (field == valueField) { var str = "#=sum#"; if (!string.IsNullOrEmpty(builderInfo.FormatSum)) { str = "#=kendo.toString(sum,'" + builderInfo.FormatSum + "')#"; } bound.ClientFooterTemplate(str); break; } } } if (builderInfo.GroupHeaderTemplate != null && builderInfo.GroupFields != null && builderInfo.GroupFields.Any()) { var header = builderInfo.GroupHeaderTemplate; foreach (var field in builderInfo.GroupFields) { if (header.ContainsKey(field) && !string.IsNullOrEmpty(header[field].ToString())) { bound.ClientGroupHeaderTemplate(header[field]); break; } } } if (!string.IsNullOrWhiteSpace(formatField)) { if (!formatField.Contains("{") || !formatField.Contains("}")) { formatField = "{0:" + formatField + "}"; } bound.Format(formatField); } if (builderInfo.HiddenFields != null && builderInfo.HiddenFields.Contains(valueField)) { bound.Hidden(true); } #endregion } //foreach (var foreignKey in builderInfo.ForeignKey) //{ // if (foreignKey.Key != null && foreignKey.Value != null && foreignKey.Value.Count() > 3) // { // IList lstFk = (IList)foreignKey.Value[2]; // if (lstFk != null) // { // if (foreignKey.Value[4].ToString() != string.Empty) // { // column.ForeignKey(foreignKey.Key.ToString(), lstFk, foreignKey.Value[0].ToString(), foreignKey.Value[1].ToString()).Width(150).Title(foreignKey.Value[3].ToString().TranslateString()).EditorTemplateName(foreignKey.Value[4].ToString()); // } // else // { // column.ForeignKey(foreignKey.Key.ToString(), lstFk, foreignKey.Value[0].ToString(), foreignKey.Value[1].ToString()).Width(150).Title(foreignKey.Value[3].ToString().TranslateString()); // } // } // } //} //column.Bound("").Title("").Sortable(false).Filterable(false).CompareByOperator(; column.Bound("").Title("").Sortable(false).Filterable(filterable => filterable .Extra(false) .Operators(ops => ops.ForString(str => str.Clear() .Contains("Contains") .StartsWith("Starts with") .EndsWith("Ends with") .IsEqualTo("Is equal to")) )); } }); #endregion #region DataSourceBuilder Action <DataSourceBuilder <T> > dataSource = new Action <DataSourceBuilder <T> >(data => { AjaxDataSourceBuilder <T> ajaxDataSource = data.Ajax(); ajaxDataSource.Events(e => e.Error("ErrorHandler")); ajaxDataSource.Batch(builderInfo.Batch); int pos = Array.IndexOf(builderInfo.ValueFields, builderInfo.DefaultSortField); if (pos > -1) { ajaxDataSource.Sort(sort => sort.Add(builderInfo.DefaultSortField).Descending()); } if (!string.IsNullOrWhiteSpace(builderInfo.EventError)) { ajaxDataSource.Events(e => e.Error(builderInfo.EventError)); } if (builderInfo.GroupFields != null && builderInfo.GroupFields.Count() > 0) { foreach (var groupField in builderInfo.GroupFields) { if (!string.IsNullOrWhiteSpace(groupField)) { ajaxDataSource.Group(group => { group.Add(groupField, GetFieldValueType(builderInfo, groupField)); }); } } } if (builderInfo.SumFields != null && builderInfo.SumFields.Count() > 0) { ajaxDataSource.Aggregates(agg => { foreach (var sumField in builderInfo.SumFields) { if (!string.IsNullOrWhiteSpace(sumField)) { agg.Add(sumField, GetFieldValueType(builderInfo, sumField)).Sum(); } } }); } if (builderInfo.PageSize > 0) { ajaxDataSource.PageSize(builderInfo.PageSize); } if (!builderInfo.ServerOperation) { ajaxDataSource.ServerOperation(builderInfo.ServerOperation); } ajaxDataSource.Model(model => { if (!string.IsNullOrWhiteSpace(builderInfo.IdPropertyName)) { model.Id(builderInfo.IdPropertyName); } foreach (var valueField in builderInfo.ValueFields) { Type fieldValueType = GetFieldValueType(builderInfo, valueField); bool editable = true; if (builderInfo.DisableFields != null) { editable = !builderInfo.DisableFields.Contains(valueField); } if (fieldValueType != null) { model.Field(valueField, fieldValueType).Editable(editable); } else { model.Field(valueField, typeof(string)).Editable(editable); } } }); if (!string.IsNullOrWhiteSpace(builderInfo.ReadActionUrl)) { if (builderInfo.ReadActionUrl.Contains("/")) { if (!string.IsNullOrWhiteSpace(builderInfo.ReadData)) { //ajaxDataSource.Read(action => action.Url(builderInfo.ReadActionUrl).Data("OverWriteReadDataOnGrid(" + builderInfo.ReadData + ")")); ajaxDataSource.Read(action => action.Url(builderInfo.ReadActionUrl).Data(builderInfo.ReadData)); } else { //Trường hợp ReadActionUrl là một đường dẫn url ajaxDataSource.Read(action => action.Url(builderInfo.ReadActionUrl)); } } else { //Trường hợp ReadActionUrl là một action name trong một controller if (builderInfo.ReadParameter != null) { ajaxDataSource.Read(builderInfo.ReadActionUrl, builderInfo.Controller, builderInfo.ReadParameter); } if (!string.IsNullOrWhiteSpace(builderInfo.ReadData)) { ajaxDataSource.Read(r => r.Action(builderInfo.ReadActionUrl, builderInfo.Controller).Data(builderInfo.ReadData)); } //ajaxDataSource.Read(builderInfo.ReadActionUrl, builderInfo.Controller); } } if (!string.IsNullOrWhiteSpace(builderInfo.CreateActionUrl)) { if (builderInfo.CreateActionUrl.Contains("/")) { //Trường hợp ReadActionUrl là một đường dẫn url ajaxDataSource.Create(action => action.Url(builderInfo.CreateActionUrl)); } else { //Trường hợp ReadActionUrl là một action name trong một controller ajaxDataSource.Create(builderInfo.CreateActionUrl, builderInfo.Controller); } } if (!string.IsNullOrWhiteSpace(builderInfo.EditActionUrl)) { if (builderInfo.EditActionUrl.Contains("/")) { //Trường hợp ReadActionUrl là một đường dẫn url ajaxDataSource.Update(action => action.Url(builderInfo.EditActionUrl)); } else { //Trường hợp ReadActionUrl là một action name trong một controller ajaxDataSource.Update(builderInfo.EditActionUrl, builderInfo.Controller); } } if (!string.IsNullOrWhiteSpace(builderInfo.DeleteActionUrl)) { if (builderInfo.DeleteActionUrl.Contains("/")) { //Trường hợp ReadActionUrl là một đường dẫn url ajaxDataSource.Destroy(action => action.Url(builderInfo.DeleteActionUrl)); } else { //Trường hợp ReadActionUrl là một action name trong một controller ajaxDataSource.Destroy(builderInfo.DeleteActionUrl, builderInfo.Controller); } } }); #endregion #region GridBuilder var gridbuilder = helper.Kendo().Grid <T>() .Name(builderInfo.Name) .Groupable(d => d.Enabled(builderInfo.ShowGroupPanel)) .AutoBind(builderInfo.AutoBind) .Resizable(d => d.Columns(true)) .Reorderable(d => d.Columns(true)) .Sortable(d => d.SortMode(GridSortMode.MultipleColumn)) .ToolBar(toolBar) .Selectable(selection) .Pageable(pageable) .Columns(columns) .ColumnMenu() .Filterable() .Editable(editing) .DataSource(dataSource) .Events(events) //.ToolBar(tb => //{ // tb.Custom().Name("ChangeColumnMode").Text("<img alt='icon' class='k-image' src='../Content/images/icons/submenu/menu/Sys_table_edit.png'>ChangeColumnMode").Url("#").HtmlAttributes(new { onclick = "ClickButtonChangeColum2('" + builderInfo.ObjectType.Name + "')" }); // tb.Custom().Name("update-inventory").Text("Update Inventory").HtmlAttributes( // new {onclick = "onUpdateInventory()", title = "Update the system inventory from the OMS", @class="k-refresh"}); //} ) ; if (!string.IsNullOrEmpty(builderInfo.ClientDetailTemplateId)) { gridbuilder.ClientDetailTemplateId(builderInfo.ClientDetailTemplateId); } IDictionary <string, object> attributes = new Dictionary <string, object>(); var strStyle = string.Empty; if (builderInfo.GridHeight > 0) { strStyle += "height:" + builderInfo.GridHeight + "px; "; } if (builderInfo.GridWidth > 0) { strStyle += "width:" + builderInfo.GridWidth + "px; "; } if (!string.IsNullOrEmpty(strStyle)) { attributes.Add("style", strStyle); } if (attributes.Any()) { gridbuilder.HtmlAttributes(attributes); } if (builderInfo.ColumnFilterable) { gridbuilder.Filterable(); } if (builderInfo.ColumnMenu) { gridbuilder.ColumnMenu(); } if (builderInfo.Scrollable) { if (builderInfo.ScrollableHeight > 0) { gridbuilder.Scrollable(s => s.Height("auto")); } else { gridbuilder.Scrollable(); } } if (builderInfo.Navigatable) { gridbuilder.Navigatable(); } if (builderInfo.ToClientTemplate) { gridbuilder.ToClientTemplate(); } return(gridbuilder); #endregion }
private void CreateGrid() { var modelName = _modelType.Name.Replace("Model", ""); GridSetupAttribute gridSetupAttribute = _modelType.GetCustomAttribute <GridSetupAttribute>(); _builder.Name("ReportListGrid"); AjaxDataSourceBuilder <T> dataSourceBuilder = null; _builder.DataSource(ds => { dataSourceBuilder = ds.Ajax(); dataSourceBuilder.Model(model => { model.Id(o => o.GetDatabaseBindings().KeyFieldName); }); dataSourceBuilder.ServerOperation(true); dataSourceBuilder.Read(r => r.Action("Read", modelName).Type(HttpVerbs.Get)); dataSourceBuilder.Create(c => c.Action("Create", modelName).Type(HttpVerbs.Post)); dataSourceBuilder.Update(u => u.Action("Update", modelName).Type(HttpVerbs.Post)); dataSourceBuilder.Destroy(d => d.Action("Destroy", modelName).Type(HttpVerbs.Post)); }); _builder.Columns(c => { dataSourceBuilder.Aggregates(a => { dataSourceBuilder.Model(m => { PropertyInfo[] modelProperties = _modelType.GetProperties(); //Incase we want to go with model attributes foreach (var p in modelProperties) { var columnAttributes = p.GetCustomAttribute <IrisGridColumnAttribute>() ?? IrisGridColumnAttribute.Default; if (p.Name.EndsWith("User_Key", StringComparison.InvariantCultureIgnoreCase)) //Give it a fake ID { m.Id(p.Name); } else { DataSourceModelFieldDescriptorBuilder <object> fieldBuilder = m.Field(p.Name, p.PropertyType); if (p.Name.EndsWith("User_Key", StringComparison.InvariantCultureIgnoreCase)) { fieldBuilder.DefaultValue(columnAttributes.GetDefaultValue()); //changed for now } else if (columnAttributes.DefaultValue != null) { fieldBuilder.DefaultValue(columnAttributes.GetDefaultValue()); } if (columnAttributes.ReadOnly) { fieldBuilder.Editable(false); } } GridBoundColumnBuilder <T> column = null; if (p.Name == "Favorite") { column = c.Bound(p.Name).ClientTemplate("<input type='checkbox' #=" + p.Name + " ? checked='checked' : '' # class='fav'></input>"); } else if (p.Name == "CustomReport") { column = c.Bound(p.Name).ClientTemplate("#=" + p.Name + " ? 'CR' : '' #").Editable("false"); } else { column = c.Bound(p.Name).Editable("false"); } column.Width(columnAttributes.Width); column.Hidden(columnAttributes.Hidden); if (p.GetCustomAttribute <DisplayFormatAttribute>() != null) { column.Format(p.GetCustomAttribute <DisplayFormatAttribute>().DataFormatString); } } }); }); }); _builder.Selectable(s => { s.Type(GridSelectionType.Row); }); _builder.Mobile(); _builder.Navigatable(); _builder.HtmlAttributes(new { style = "height: 700px; width: 350px" }); _builder.Scrollable(a => a.Height("100%")); _builder.Events(x => { x.DataBound("ReportListDataBound"); }); _builder.Editable(e => e.Mode(GridEditMode.InLine).Enabled(true)); }
public static GridBuilder <T> GridControl <T>(this HtmlHelper helper, GridInfomation grid) where T : class { grid.ObjectType = grid.ObjectType != null ? grid.ObjectType : typeof(T);//Kiểu dữ liệu của đối tượng đang xét trên lưới. Action <GridSelectionSettingsBuilder> selection = new Action <GridSelectionSettingsBuilder>(d => d.Mode(GridSelectionMode.Single)); Action <PageableBuilder> pageable = new Action <PageableBuilder>(d => d.PageSizes(true).Refresh(true).ButtonCount(5)); Action <GridColumnFactory <T> > columns = new Action <GridColumnFactory <T> >(column => { if (grid.ValueFields != null) { column.AutoGenerate(false); foreach (var valueField in grid.ValueFields) { GridBoundColumnBuilder <T> bound = null; Type fieldValueType = null; if (grid.TypeFields != null && grid.TypeFields.Any(d => d.Key == valueField)) { fieldValueType = grid.TypeFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); } else if (grid.ObjectType != null && grid.ObjectType.HasProperty(valueField)) { fieldValueType = grid.ObjectType.GetPropertyType(valueField); } if (fieldValueType != null) { bound = column.Bound(fieldValueType, valueField); } else { bound = column.Bound(valueField); } if (grid.HasDisplayFields()) { string displayField = grid.DisplayFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(displayField)) { bound.Title(displayField); } } if (grid.InvisibleFields != null) { bound.Visible(!grid.InvisibleFields.Contains(valueField)); } if (grid.HasFormatFields()) { string formatField = grid.FormatFields.Where(d => d.Key == valueField).Select(d => d.Value).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(formatField)) { bound.Format(formatField); } } } //1. Tạo command muốn hiển thị //column.Command(cmd => //{ // cmd.Edit(); //// //cmd.Custom("Change").Click("showpage"); //// //cmd.Custom("Edit").Click("ShowInfoCatBankEdit"); // cmd.Destroy(); //}).Width(300); } }); Action <DataSourceBuilder <T> > dataSource = new Action <DataSourceBuilder <T> >(d => { AjaxDataSourceBuilder <T> ajaxDataSource = d.Ajax(); //2. Xác định được id tương ứng khi click vào một record trên lưới ajaxDataSource.Model(m => m.Id(grid.ValueFields[0])); if (grid.PageSize > 0) { ajaxDataSource.PageSize(grid.PageSize); } if (!string.IsNullOrWhiteSpace(grid.IdPropertyName)) { ajaxDataSource.Model(model => model.Id(grid.IdPropertyName)); } if (!string.IsNullOrWhiteSpace(grid.Url)) { ajaxDataSource.Read(read => read.Url(grid.Url).Type(HttpVerbs.Post)); //ajaxDataSource.Update(read => read.Url(grid.EditUrl).Type(HttpVerbs.Post)); ////ajaxDataSource.Create(read => read.Url(grid.InsertUrl).Type(HttpVerbs.Post)); } if (!string.IsNullOrWhiteSpace(grid.InsertActionName)) { ajaxDataSource.Update(grid.EditActionName, grid.EditControllerName); //ajaxDataSource.Read(grid.DataActionName, grid.ControllerName); ajaxDataSource.Create(grid.InsertActionName, grid.InsertControllerName); //3. Phải xác định dược controller và action áp dụng cho nút xóa ajaxDataSource.Destroy(grid.DeleteActionName, grid.DeleteControllerName); } }); var gride = new Action <GridEventBuilder>(e => { if (!string.IsNullOrWhiteSpace(grid.Change)) { e.Change(grid.Change); } }); return(helper.Kendo().Grid <T>() .Name(grid.GridName) .Sortable() .Scrollable() //.ToolBar(t => //{ // t.Create(); // //t.Custom().Text("Add").Url("#").HtmlAttributes(new { onclick = "NewPageInsert()" }); // //t.Custom().Text("Add new").Url("#").HtmlAttributes(new { onclick = "ShowDivInsert()" }); //}) .Groupable() .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName(grid.TemplateName)) .Selectable(selection) .Pageable(pageable) .Columns(columns) .DataSource(dataSource) .Events(gride)); }