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.
Unfortunately, activation email could not send to your email. Please try again.

Error serialize json in grid

Thread ID:

Created:

Updated:

Platform:

Replies:

117447 Oct 21,2014 04:01 PM Feb 11,2016 08:09 AM ASP.NET Web Forms 13
loading
Tags: Grid
Roimer Machacón Otero
Asked On October 21, 2014 04:01 PM

Hi, we are using the grid, now when the grid receive the data, this error is appearing:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

The number of records in json is around of 7500 records. Us in the web.config file have define this:

<configuration>  
<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483644"/>      
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

Thinking that the error can solved in this form but this not work.

Now reviewing in the stacktrace in visual studio we can see that the error is related with Syncfusion.JavaScript.Shared.Serializer.SerializeObject.DataTableToJson. (Attached image with this information).

Exist a form of define the max length for a json in reference to Syncfusion Grid objects???

Attachment: Error_3ff048a1.rar

Roimer Machacón Otero
Replied On October 22, 2014 12:37 PM

Attached to this post the Json that generate the error.

Us in the function when bring the datatable to convert to Json use this lines

Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
serializer.MaxJsonLength = Integer.MaxValue

At this point the Json is correctly, the error ocurrs when is received for the grid

Attachment: LoadJSONErrorEjGrid_30ba02b3.rar

Alan Sangeeth S [Syncfusion]
Replied On October 23, 2014 07:30 AM

Hi Nestor,

 

We have used the default MaxJsonLength value (2097152 characters, which is equivalent to 4 MB of Unicode string data) of the JavaScriptSerializer while serializing the datasource. We tried to serialize the datasource by setting the MaxJsonLength manually and it serialized the data successfully but it thrown “System.OutOfMemory Exception”. Hence we suggest you to avoid populating the grid with more data directly instead use On-Demand paging Grid which loads only required records for the current page

 

We can also use custom serailizer to serialize the dataSource, this can be done as follows.

Custom datasource serializer class will be as follows.

public class DMSerial : IDataSourceSerializer {

public string Serialize(object obj)

{

var str = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

return str;

}

}

And the custom serializer can be assigned as follows.

@{

DataManagerConverter.Serializer = new DMSerial();

}

Eventhough custom serializer serialize large amount of data, it will also lead to out of memory exception.

 

For your convenience we have created the sample using “On-Demand” paging and the same can be downloaded from the below link

Sample Link : http://www.syncfusion.com/downloads/support/directtrac/131094/Sample-959640018-1785828612.zip

 

In the above sample using “Load” event of Grid we have created custom adaptor to bind data from server-side to Grid dataSource. Please refer the below code snippet

ej:Grid ID="EmployeesGrid" runat="server" AllowPaging="true" Load="loadHandler">
<
DataManager URL="Default.aspx/Data"/>
...
</
ej:Grid>

var adaptor = new ej.UrlAdaptor().extend({

             processResponse: function (data, ds, query, xhr, request, changes) {

 

                 return data.d;

             }

         });

         function loadHandler(args) {

             args.model.dataSource.dataSource.batchUrl = "Default.aspx/Update"

             args.model.dataSource.adaptor = new adaptor();

         }

Also when we use on-demand paging Grid, we need to return the data as JSON and the JSON object must contain field name as “result” with its value as dataSource and one more field name as “count” with its value as dataSource total records count.

 

 While paging “skip” and “take” values will be passed to server –side by which we can filter records needed for current page. Please refer the following code snippets.

public static object Data(int skip, int take)

        {

var DataSource = OrderRepository.GetAllRecords();

            DataResult ds = new DataResult();

          ds.result=DataSource.Skip(skip).Take(take);

           ds.count= ds.count = DataSource.Count();

           return ds;

   }

Please try the above sample and please let us know if you have any queries.

Regards,

Alan Sangeeth S


Roimer Machacón Otero
Replied On October 23, 2014 05:14 PM

Hi Alan, thank you for your quickly response.
The example that you gave us was about working with MVC. We are working with Web Form. Can you give us an example using web form instead MVC?
Also, I tried to serialize the same object and it works without exceptions.

regars!!

Alan Sangeeth S [Syncfusion]
Replied On October 24, 2014 02:37 AM

Hi Nestor,

 

Thanks for the update.

 

Query 1: “example using web form”

 

We are sorry for the inconvenience caused. We suspect that you are asking about the custom serializer example and so in the below code snippets we have provided you the equivalent web form code.

public class DMSerial : IDataSourceSerializer

        {

 

            public string Serialize(object obj)

            {

 

                var str = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

 

                return str;

 

            }

 

        }

        protected void Page_Load(object sender, EventArgs e)

        {

 

            DataManagerConverter.Serializer = new DMSerial();

            this.EmployeesGrid.DataSource = OrderRepository.GetAllRecords();

                this.EmployeesGrid.DataBind();

        }

 

But we would like to let you know that the above custom serializer also throws out of memory exception and so we have provided On-Demand paging Grid sample in the previous response.

 

Query 2: “serialize the same object and it works without exceptions”

 

We could not understand what object you are serializing and the scenario in which you are doing it. Could you please send us more information about it so that we could provide you a response as early as possible?

Please let us know if you have any queries.

Regards,

Alan Sangeeth S


Roimer Machacón Otero
Replied On December 17, 2014 04:40 PM

Hi, We've seen the example and this is ok, now we could implement something similar in webforms with vb.net. 

Can you help us with an example of this style?

Alan Sangeeth S [Syncfusion]
Replied On December 18, 2014 06:30 AM

Hi Nestor,

Thanks for the update

We have modified the sample based on your requirement (“Webforms with VB language”) and the same can be downloaded from below link.

Sample: http://www.syncfusion.com/downloads/support/directtrac/133118/ASPVB1340218343.zip

Please let us know if you need any further assistance.

Regards,
Alan Sangeeth S


Roimer Machacón Otero
Replied On December 18, 2014 08:39 AM

Hi, the example in vb.net is ok. Now this connect directly to design of the database, we are bringing a table of a query result.

How can we pass the resulting table for use skip and take

"ds.result = DataSource.Skip(skip).Take(take)"

Alan Sangeeth S [Syncfusion]
Replied On December 19, 2014 04:34 AM

Hi Nestor,

 

Thanks for the update.

 

We suggest you to convert the DataTable to List to achieve you requirement. Please refer the following code snippets.

 

Public Shared Function Data(skip As Integer, take As Integer) As Object

 

 

        Dim t As New DataTable()

        Using c As New SqlConnection()

...

            Using a As New SqlDataAdapter("SELECT * FROM Orders", c)

                a.Fill(t)

            End Using

        End Using

 

        Dim convertedList As New List(Of Order)()

 

        For Each dr As DataRow In t.Rows

            Dim objPC As New Order()

            objPC.OrderID = Convert.ToInt32(dr("OrderID"))

            objPC.ShipCity = dr("ShipCity").ToString()

            objPC.Freight = Convert.ToDecimal(dr("Freight"))

            convertedList.Add(objPC)

        Next

 

        Dim ds As New DataResult()

        ds.result = convertedList.Skip(skip).Take(take).ToList()

        ds.count = convertedList.Count()

        Return ds

 

    End Function

 

 

For your convenience we have created a sample based on your requirement and the same can be downloaded from below link.

 

Sample: http://www.syncfusion.com/downloads/support/directtrac/133118/ASPVB2004693203.zip

 

Please let us know if you need any further assistance.

Regards,
Alan Sangeeth S


Roimer Machacón Otero
Replied On December 19, 2014 09:05 AM

The example work ok, Now to the method, how to pass a value different of skip and take that come of a textbox in the aspx? Or how can we in the code of the method request a value write in a textbox in the aspx, for example

"Public Shared Function Data(skip As Integer, take As IntegerAs Object"
    Dim plan = txtPlan.text (This line not recognized in the method being that the textbox is in the aspx)


Roimer Machacón Otero
Replied On December 19, 2014 09:38 AM

This for load the data in the grid dynamically depending of a value

Alan Sangeeth S [Syncfusion]
Replied On December 22, 2014 04:17 AM

Hi Nestor,

 

Thanks for the update.

 

Query 1: “how to pass a value different of skip and take”

 

We would like to let you know that we can pass additional parameter using “query” Grid property in “ActionBegin” Grid event. For your convenience we have created a sample and the same can be downloaded from below link.

 

Sample: http://www.syncfusion.com/downloads/support/directtrac/132804/ASPVB-1864902395.zip

 

In the above sample based on the value in textbox we have filtered Grid datasource with Freight Column. Please refer the following code snippets.

 

<asp:TextBox ID="TextBox1" runat="server" Text="50"></asp:TextBox>

...

            <ContentTemplate>

        <ej:Grid ID="Grid1" runat='server' AllowPaging="true" ActionBegin="actionBegin" Load="loadHandler">

            <DataManager URL="Sample.aspx/Data" Adaptor="UrlAdaptor"  />

           ...

        <PageSettings PageSize="5" />

 

        </ej:Grid>

 

function actionBegin(args) {

              this.model.query.addParams("txtBox", $("#TextBox1").val())

          }

Public Shared Function Data(skip As Integer, take As Integer, txtBox As String) As Object
...

convertedList = convertedList.Where(Function(s) s.Freight < Convert.ToDecimal(txtBox)).ToList()

        ds.result = convertedList.Skip(skip).Take(take).ToList()

        ds.count = convertedList.Count()

        Return ds

 

Query 2: “how can we in the code of the method request a value write in a textbox in the aspx”

 

We would like to let you know that we cannot access instance member of class in shared method (eg., Data Method in above sample). Please refer the following link.

 

http://msdn.microsoft.com/en-us/library/xfsswe45.aspx

 

But we can achieve it by using a shared variable that has Textbox control. Please refer the following code snippets.

 

<asp:TextBox ID="TextBox1" runat="server" Text="50"></asp:TextBox>

 

Public Class Sample

    Inherits System.Web.UI.Page

    Private order As New List(Of Orders)()

    Shared TextBox = Nothing

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

 

        TextBox = TextBox1

 

    End Sub

Public Shared Function Data(skip As Integer, take As Integer) As Object

 

 

...

 

        convertedList = convertedList.Where(Function(s) s.Freight < Convert.ToDecimal(TextBox.Text)).ToList()

        ds.result = convertedList.Skip(skip).Take(take).ToList()

        ds.count = convertedList.Count()

        Return ds

 

    End Function

Please let us know if you need any further assistance.

Regards,
Alan Sangeeth S


Roimer Machacón Otero
Replied On February 10, 2016 09:13 AM

Hi, we're using the last example and this work correctly in the version 12.2.0.36, now we updated to the last version of 2014 12.4.0.34, and the example in this version not work, the grid seeing in debug mode not enter in the url used in the datamanager.

Here is the code used for us:

"Aspx"

<script>
        var adaptor = new ej.UrlAdaptor().extend({
            processResponse: function (data, ds, query, xhr, request, changes) {
                if (data.d)
                    data = data.d
                return ej.UrlAdaptor.prototype.processResponse.apply(this, [data, ds, query, xhr, request, changes])
                //return data.d;
                //console.log(data.d);
            }
        });
        function loadHandler(args) {
            args.model.dataSource.adaptor = new adaptor();
        }

        function actionBegin(args) {
            this.model.query.addParams("codigoPlan", $("#hdfNumeroPlan").val())
        }
</script>


<ej:Grid ID="gvsDetalle" runat="server" AllowGrouping="false" AllowSelection="true" TabIndex="-1" Locale="es-ES"
  Selectiontype="Single" AllowSorting="True" AllowPaging="True" AllowFiltering="false"
  RowSelected="filaSeleccionada" BeforeBatchSave="eliminarDetalle" BatchDelete="limpiarGrillaRecursos"
  Load="loadHandler" ActionBegin="actionBegin">
  <DataManager URL="PlanesAccionNuevo.aspx/CargarDetallesPlan" Adaptor="UrlAdaptor" />
  <PageSettings PageSize="10" />
  <FilterSettings FilterType="FilterBar" FilterBarMode="OnEnter" />
  <GroupSettings EnableDropAreaAutoSizing="False"></GroupSettings>
  <Columns>
    <ej:Column Field="Codigo" HeaderText="<%$ Resources:PlanAccion, idDetalle %>" IsPrimaryKey="true" Width="10%" />
    <ej:Column Field="Lote" HeaderText="<%$ Resources:Generales, lote %>" Width="8%" />
    <ej:Column Field="Linea" HeaderText="<%$ Resources:Generales, linea %>" Width="8%" />
    <ej:Column Field="Palma" HeaderText="<%$ Resources:Generales, palma %>" Width="8%" />
    <ej:Column Field="Actividad" HeaderText="<%$ Resources:PlanAccion, codActividad %>" Width="14%" />
    <ej:Column Field="NombreActividad" HeaderText="<%$ Resources:PlanAccion, nomActividad %>" Width="20%" />
    <ej:Column Field="Rendimiento" HeaderText="<%$ Resources:Generales, rendimiento %>" Width="14%" />
    <ej:Column Field="NoRevision" HeaderText="<%$ Resources:PlanAccion, revisionAsociada %>" />
  </Columns>
  <EditSettings AllowEditing="False" AllowAdding="True" AllowDeleting="True" EditMode="Batch"></EditSettings>
  <ToolbarSettings ShowToolbar="true" ToolbarItems="delete,update,cancel,search"></ToolbarSettings>
</ej:Grid>


"Code behind"

<WebMethod()> _
        <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Shared Function CargarDetallesPlan(skip As Integer, take As Integer, codigoPlan As String) As Object
        Dim implementacionPlanAccion = New ImplementacionPlanAccion
        Try
            Dim listaDetalles = implementacionPlanAccion.listarDetallesGrilla(-1, codigoPlan)
            Dim entidad As New PlanAccionDetalleEntidadResult()
            entidad.result = listaDetalles.Skip(skip).Take(take).ToList()
            entidad.count = listaDetalles.Count()
            Return entidad

        Catch ex As Exception
            Throw ex
        End Try
    End Function



Venkatesh Ayothi Raman [Syncfusion]
Replied On February 11, 2016 08:09 AM

Hi Roimer,

We have analyzed your code but we were unable to reproduce the issue. For your convenience we have created a sample  using url adaptor with given the workaround.

Sample: http://www.syncfusion.com/downloads/support/directtrac/general/ze/GridSample699954141

Code Snippet:

asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">



    <div>

        <asp:UpdatePanel runat="server" >

            <ContentTemplate>

                <ej:Grid ID="EmployeesGrid" runat="server"   Load="loadHandler"  Create="create" AllowPaging="true" Width="1500px" OnServerEditRow="EmployeesGrid_ServerEditRow">

            <EditSettings AllowAdding="True" AllowEditing="True" AllowDeleting="True" ></EditSettings>

                    <ToolbarSettings ShowToolbar="true" ToolbarItems="add,delete,update,cancel"></ToolbarSettings>

           <DataManager URL="/Default.aspx/Data"   Adaptor="UrlAdaptor" />

                    <ClientSideEvents Load="loadHandler" />

           

    <script>

        var adaptor = new ej.UrlAdaptor().extend({

            processResponse: function (data, ds, query, xhr, request, changes) {

                if (data.d)

                    data = data.d

                return ej.UrlAdaptor.prototype.processResponse.apply(this, [data, ds, query, xhr, request, changes])

               

            }

        });

        function loadHandler(args) {

            args.model.dataSource.adaptor = new adaptor();

        }


        function actionBegin(args) {

            this.model.query.addParams("codigoPlan", $("#hdfNumeroPlan").val())

        }

</script>

</asp:Content>


Note:
We provide support for the web method adaptor from “12.4.0.34” version. In that adaptor, we can  access all the server side operations. If you upgrade the version to “12.4.0.34” from “12.2.0.36” then above mentioned workaround is not required. And you have to use also webmethod adaptor instead of Url adaptor.
Refer to the documentation for your more information.
 https://www.syncfusion.com/kb/4300/server-side-api-for-datamanager-operations

For your convenience we have created a sample for that also.
Sample: http://www.syncfusion.com/downloads/support/directtrac/general/ze/Sample21194632698

Please let us know if you have any further queries.
Regards,
Venkatesh Ayothiraman.

CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.

;