We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Grid Export to Excel - Controller

Hi, I'm trying to generate a report in Excel. But the following error occurs: 

Invalid primitive JSON: "EmptyRecord":"No records to display","GroupCaptionFormat":"{{:headerText}}: {{:key}} - {{:count}} ","GroupText":" item","True":"true","False":"false"}.
System.ArgumentException: JSON primitivo inválido: "EmptyRecord":"No records to display","GroupCaptionFormat":"{{:headerText}}: {{:key}} - {{:count}} ","GroupText":" item","True":"true","False":"false"}.

Html.EJ()
                .Grid<TravelAccountability.Web.ViewModels.ExpenseTypesListViewModel>
                    ("gridExpenseTypes")
                    .Locale(Culture)
                    .AllowTextWrap()
                    .AllowPaging().PageSettings(page => { page.PageSize(10); })
                    .AllowKeyboardNavigation(false)
                    .IsResponsive(true)
                    .EditSettings(
                    edit =>
                    {
                        edit.AllowAdding()
                        .AllowDeleting()
                        .AllowEditing()
                        .EditMode(EditMode.Normal);
                    }
                    )
                    .ClientSideEvents(
                    eve =>
                    {
                        eve
                        .ActionComplete("querycell")
                        .ActionBegin("begin")
                        .BeginEdit("beginedit")
                        .EndEdit("endEdit")
                        .EndAdd("endAdd");
                    }
                    )
                    .ToolbarSettings(
                    toolbar =>
                    {
                        toolbar.ShowToolbar()
                        .ToolbarItems(
                        items =>
                        {
                            items.AddTool(ToolBarItems.ExcelExport);
                            items.AddTool(ToolBarItems.Add);
                            items.AddTool(ToolBarItems.Edit);
                            items.AddTool(ToolBarItems.Delete);
                            items.AddTool(ToolBarItems.Update);
                            items.AddTool(ToolBarItems.Cancel);
                        }
                        );
                    }
                    )
                    .AllowFiltering()
                    .FilterSettings(
                    filter => { filter.FilterType(FilterType.Excel); }
                    )
                    .Datasource(x => x.Json(Model.ExpenseTypes)
                    .InsertURL(Url.Action("SaveExpenseType", "Administration"))
                    .UpdateURL(Url.Action("UpdateExpenseType", "Administration"))
                    .RemoveURL(Url.Action("RemoveExpenseType", "Administration"))
                    .Adaptor(AdaptorType.RemoteSaveAdaptor))

                    .Columns(
                    col =>
                    {
                        col
                            .Field(c => c.ExpenseTypeID).IsPrimaryKey(true)
                                .Visible(false).Add();

                        col
                            .Field(c => c.Description).Priority(1).IsIdentity(true)
                                .ValidationRules(v => v
                                    .AddRule("validationRequired", 0)
                                    .AddRule("validationMax50", 50)
                                    .AddRule("messages", "{required:'" + Resource.ExpenseTypesListViewModel_DescriptionValidation + "'}")
                                )
                            .Add();

                        col
                            .Field(c => c.FiscalAccount).Priority(2).EditType(EditingType.String)
                                .ValidationRules(v => v
                                .AddRule("validationRequired", 0)
                                .AddRule("validationMax8", 8)
                                .AddRule("messages", "{required:'" + Resource.ExpenseTypesListViewModel_FiscalAccountValidation + "'}")
                                )
                                .Add();

                        col
                            .Field(c => c.IsActive).Priority(3).Visible(true).EditType(EditingType.Boolean)
                                .Width("105px").HeaderTextAlign(TextAlign.Right).TextAlign(TextAlign.Center)
                                .Add();

                        col
                            .Field(c => c.IsDailyExpenseRate).Visible(false)
                            .Add();

                        col
                            .Field(c => c.CreatedOnString).Visible(false).EditType(EditingType.String)
                            .Add();

                        col
                            .Field(c => c.CreatorRE).Visible(false).DefaultValue(Model.CreatorRE)
                            .Add();

                        col
                            .Field(c => c.ModifiedOnString).Visible(false).EditType(EditingType.String)
                            .Add();

                        col
                           .Field(c => c.ModifierRE).Visible(false).DefaultValue(Model.ModifierRE)
                           .Add();

                        col
                           .Field(Resource.ExpenseTypeViewModel_Details).Priority(1)
                           .AllowEditing(false)
                           .AllowFiltering(false)
                           .Template("#actionColumnTemplateDetail")
                           .Width("120px")
                           .TextAlign(TextAlign.Center)
                           .Add();

                    }).Render();


<script type="text/x-jsrender" id="actionColumnTemplateDetail">
    <div>
        <button type="button" class="btn btn-primary btnOpenDetail" data-toggle="tooltip" data-placement="right"
                onclick="openDetailDialog(this);"
                title="@Resource.ExpenseTypeViewModel_BtnDetailsTitle">
            <span class="fa fa-search-plus" style="margin-left: auto;"></span>
        </button>
    </div>
</script>

//Controller

        public void ExportToExcel(string GridModel)
        {
            ExcelExport exp = new ExcelExport();
            var GridModel = string.Empty;
            var DataSource = new ExpenseTypesListViewModel().ExpenseTypes.ToList();
            GridProperties obj = ConvertGridObject(GridModel);

            exp.Export(obj, DataSource, "Export.xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");  the line where the error occurs
            return View();
        }

private GridProperties ConvertGridObject(string gridProperty)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            IEnumerable div = (IEnumerable)serializer.Deserialize(gridProperty.ToString(), typeof(IEnumerable));
            GridProperties gridProp = new GridProperties();
            foreach (KeyValuePair<string, object> ds in div)
            {
                var property = gridProp.GetType().GetProperty(ds.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                if (property != null)
                {
                    Type type = property.PropertyType;
                    string serialize = serializer.Serialize(ds.Value);
                    object value = serializer.Deserialize(serialize, type);
                    property.SetValue(gridProp, value, null);
                }
            }
            return gridProp;
        }

1 Reply

SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team November 22, 2016 10:56 AM UTC

Hi Gilherme,  

Thanks for contacting Syncfusion support.  

We are unable to reproduce the problem at our end with the provided code example. 

We could see “var GridModel = string.Empty;” and later it has been serialized/deserialized in the ConvertGridObject method. We suspect this would be cause of the problem. So please ensure whether it is needed your at end. Since GridModel is the parameter (grid model) sent from the Grid which has been used for Exporting the Grid, you must not empty it. The Locale for the Grid has been assigned to the Grid dynamically. Please ensure whether it’s value is correctly assigned or not.  

We have also created a sample that can be download from following location,  
 
  
If you still face the same issue, then could you please share the following details?  

1)     Sample data that bind to the Grid. 
2)     Screenshot of exception.  
3)     Provide the details of culture and code example.  
4)     Provide your sample if possible or modified the given sample as issue reproducible.  

We are also suspecting the issue arises from the Data Bound to the Grid. If provide the sample data, which would be very helpful to analyze the issue. 

Regards,  
Seeni Sakthi Kumar S. 


Loader.
Live Chat Icon For mobile
Up arrow icon