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

Grid refresh after AJAX success

Hi, 

I'm having trouble refreshing the grid after the ajax call

This is the code:

<asp:Content ID="Content3" ContentPlaceHolderID="cphMain" runat="server">               
  <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
    <ContentTemplate>
      <div style="padding-top:20px"> 
       <ej:Button ID="open" runat="server" Text="open" ClientSideOnClick="openDialog"></ej:Button> 
       <ej:Button ID="refresh" runat="server" Text="refresh" ClientSideOnClick="refreshGrid"></ej:Button>
       <ej:Grid ID="Grid1" runat='server' AllowSorting="True" AllowTextWrap="True" DataSourceCachingMode="None" OnServerExcelExporting="FlatGrid_ServerExcelExporting">         
          <Columns>
                        . 
.
.
.
</Columns>      
       </ej:Grid>  
                       </div>  
       <div id="dlg" style="visibility:hidden" class="control">
       <ej:Dialog ID="dialog" Title="Unos" ShowOnInit="false" runat="server" ShowRoundedCorner="true">
       <DialogContent>
                <table id="Unos" border="0" style="width:100%" runat="server" class="gg">
                <tbody>
               .
  .
  .
  .
  .
  
                    </tbody>
            </table>   
                    <hr class="style-one"/>             
            <ej:Button runat="server" Text="Save" ClientSideOnClick="Save" ID="saveButton" Type="Button" Size="Small" ShowRoundedCorner="true" ContentType="TextAndImage" PrefixIcon="e-save" />                                       
        </DialogContent>
    </ej:Dialog>  
    </div>          
   </ContentTemplate>
    </asp:UpdatePanel>                         
</asp:Content>

<script type="text/javascript">
function refreshGrid() {
            var obj = $("#Grid1").ejGrid("instance");
            obj.refreshContent();
        };  
function openDialog() {          
                $(".dlg").show()
                $("#dialog").ejDialog("open");            
        }
function Save() {           
            var obj = $("#Grid1").ejGrid("instance");            
            var data = {
                .
.
.
.
.
            }
            var params = "{'dataPackage': '" + JSON.stringify(data) + "'}";           
            $.ajax({
                type: "POST",
                url: "Default.aspx/Save",
                async: true,
                data: params,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {                                        
                        var obj = $("#Grid1").ejGrid("instance");
                        obj.refreshContent();                    
                },
                error: function (request, status, error) {
                    toastr.warning(request.responseText);
                }
            });  
        }
    </script>

The refresh button above the grid works fine and refreshes without postback.
The problem is the Save button/function after success when calling the obj.refreshContent();  

Any help appriciated.

7 Replies

PK Prasanna Kumar Viswanathan Syncfusion Team June 30, 2016 09:55 AM UTC

Hi Pratura, 

Thank you for contacting Syncfusion support.   
 
When we call the refresh content method, the postBack will not be triggered. The postBack has been triggered due to the button click  
 
When we click the button inside the dialog, the postback has not been triggered. The root cause is you have mentioned the type as button in the save button and button has been rendered outside the form element  

Find the code example: 


<ej:Button ID="open" runat="server" Text="open" ClientSideOnClick="openDialog" Type="Button"></ej:Button> 


If you need to trigger the server side while refreshing the grid, use PageMethods mechanism of the ASP.NET application. The PageMethods acts similar to that of the AJAX call. We have triggered a server-side event using PageMethods in the actionComplete event of the Grid.   
  
Find the code example and sample:   
 

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent"> 
  <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always"> 
      <ContentTemplate> 
       <div style="padding-top:20px"> 
        <ej:Button ID="open" runat="server" Text="open" ClientSideOnClick="openDialog"></ej:Button>  
        ------------------------------ 
       <ej:Grid ID="Grid" runat="server" AllowTextWrap="true" AllowSorting="true" OnServerExcelExporting="Grid_ServerExcelExporting" AllowPaging="true"> 
            <Columns> 
                ----------------------------------------- 
           </Columns> 
         <ClientSideEvents ActionComplete="complete" /> 
 
--------------------------------------- 
function complete(args) { 
        if (args.requestType == "refresh") { 
            PageMethods.GetRefresh(); 
        } 
    }        
----------------------------------------- 

[System.Web.Services.WebMethod] 
        public static string GetRefresh() 
        { 
            ----- 
        } 


Regards, 
Prasanna Kumar N.S.V 
 



PR Pratura July 1, 2016 12:38 PM UTC

Thank you.

When using your method all i see is that function complete(args) fires a lot of time even when there is no refresContent called.
But i don't understand the GetRefresh static on the server. 
I still don't know how to refresh the grid after success. 
The static method won't allow server side control methods




PK Prasanna Kumar Viswanathan Syncfusion Team July 4, 2016 11:32 AM UTC

Hi Pratura, 
 
Please let us know whether your issue is, when you click the refreshButton the grid is refreshed without postback. But when you click the save button inside the dialog, the postback has not been triggered when grid has been refreshed.   
 
This is because you have mentioned the type as button in the save button and also the button has been rendered outside the form element. So, in this case the postback will not be triggered when you click outside the refresh button or inside the dialog button.   
 
Query 1: When using your method all i see is that function complete(args) fires a lot of time even when there is no refresContent called. 
 
We have checked your code example, and the postback issue is not reproduced at our end. We suspect that you want server side call while refreshing the grid content. So, use the actionComplete event of ejGrid and call the pager method when the grid is refreshed by checking “requestType” as “refresh”. This event is triggered for every grid action success event. In the code example, we check the condition with the requestType “refresh”, so the server side event will be triggered using PageMethods when we refresh the grid. If you do not want to trigger the server-side event, you can remove the actionComplete event.   
 
Query 2: I still don't know how to refresh the grid after success.  
 
We suspect that you have returned JSON data in the ajax post and reloaded the grid data using the arguments(response). If you want to reload the grid data, use DataSource method of ejGrid.    
 
Please find the below code snippet 
 
 
var grid = $("#Grid").ejGrid("instance"); 
 
grid.dataSource(response);  
 
 
Refer to the Help document for the DataSource method.   
 
 
 
Please provide the following details,   
 
1. Purpose of calling the refreshContent method inside AJAX success.   

2. You have mentioned the static method won’t allow the server side control methods. Can you please elaborate this query?  

Regards, 
Prasanna Kumar N.S.V 
 
 



PR Pratura July 4, 2016 01:26 PM UTC

Thank you for the reply.

1.Purpose of calling the refreshContent method inside AJAX success.
I want to refresh the grid after the AJAX sends the data for inserting a new row into the database
The grid needs to be refreshed so the new row is visible.

The save method was a Sub, but even when changing it to function that returns an object to the successfunction (response)
and then setting the grid datasourcegrid.dataSource(response);i get an error:

A circular reference was detected while serializing an object of typeSystem.Web.Script.Serialization.JavascriptSerializer...

My grid gets its data on PageLoad like this:

Dim db As New Db
Grid1.DataSource = db.getData("xxxx_Select")
Grid1.DataBind()
And the Save function is now this:
<code>
<WebMethod>
Public Shared Function Save(ByVal dataPackage As String) As Object
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim values As Dictionary(Of String, String) = js.Deserialize(Of Dictionary(Of String, String))(dataPackage)
Dim db As New Db
Dim CMD As New SqlCommand("xxxx_Insert")
CMD.Parameters.Add("@id", SqlDbType.Int)
CMD.Parameters("@id").Value = CInt(values.Item("ID"))
.
.
.
.
db.ExecuteStoredProcedure(CMD)
Dim o As Object = db.getData("xxxx_Select")
Return o
End Function
</code>
db.GetData returns DataTable
So if i could return the datasource to response it would probably work if you can help.



SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team July 5, 2016 12:48 PM UTC

Hi Pratura, 

We could see that you would like to refresh the Grid after inserting a record in the success method of ajax call.  

By default Grid provides this way by using WebMethodAdaptor. In WebMethodAdaptor, the Grid will repopulate the content after every successful CRUD operation like Insert/Edit/Delete. This method doesn’t require any explicit method to refresh the Grid content. Refer to the following code example and Help Document. 

    <ej:Grid ID="Grid1" runat='server' AllowPaging="true"> 
        <DataManager URL="Default.aspx/DataSource" UpdateURL="/Default.aspx/PerformUpdate" InsertURL="Default.aspx/PerformInsert" RemoveURL="Default.aspx/PerformDelete" Adaptor="WebMethodAdaptor" /> 
        <EditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" /> 
        <ToolbarSettings ShowToolbar="true" ToolbarItems="add,edit,delete,update,cancel" /> 
        <Columns> 
            <ej:Column Field="OrderID" IsPrimaryKey="true" Width="80" /> 
            <ej:Column Field="CustomerID" Width="100" /> 
            <ej:Column Field="EmployeeID" Width="80" /> 
            <ej:Column Field="Freight" Format="{0:C2}" Width="80" /> 
        </Columns> 
    </ej:Grid> 
 
   <WebMethod> _ 
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ 
    Public Shared Function DataSource(value As Syncfusion.JavaScript.DataManager) As Object 
        Dim Data As IEnumerable = New NorthWNDDataContext().OrderTables.ToList() 
        Dim count As Integer = Data.AsQueryable().Count() 
        Dim operation As New Syncfusion.JavaScript.DataSources.DataOperations() 
        Data = operation.Execute(Data, value) 
        Return New With { _ 
            Key .result = Data, _ 
            Key .count = count _ 
        } 
    End Function 
 
 
    <WebMethod> _ 
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ 
    Public Shared Sub PerformInsert(value As OrderTable) 
       . . ..  
        db.SubmitChanges() 
    End Sub 
 
    <WebMethod> _ 
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ 
    Public Shared Sub PerformUpdate(value As OrderTable) 
        . . . 
        db.SubmitChanges() 
    End Sub 
    <WebMethod> _ 
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ 
    Public Shared Sub PerformDelete(key As Integer) 
           .. .  
        db.SubmitChanges() 
    End Sub 


From your previous responses, we also could see that you are updating the Grid using some external actions. By using the CRUD methods like, addRecord, updateRecord, deleteRecord, you can update the Grid records which will also doesn’t need explicit method like refreshContent to repopulate. Using CRUD Methods, the Grid will be repopulated as well as update corresponding the record in database. Refer to the following code example and Help Document. 

    <ej:Button ID="open" runat="server" Text="open" ClientSideOnClick="openDialog" Type="Button"></ej:Button> 
 
    <ej:Grid ID="Grid" runat='server' AllowPaging="true"> 
        <DataManager URL="Default.aspx/DataSource" UpdateURL="/Default.aspx/PerformUpdate" InsertURL="Default.aspx/PerformInsert" RemoveURL="Default.aspx/PerformDelete" Adaptor="WebMethodAdaptor" /> 
              . . . . . 
    </ej:Grid> 
    <div id="dlg" style="visibility: hidden" class="control"> 
        <ej:Dialog ID="dialog" Title="Unos" ShowOnInit="false" runat="server" ShowRoundedCorner="true"> 
            <DialogContent> 
                <ej:Button Text="Save" runat="server" ClientSideOnClick="Save" ID="saveButton" Size="Small" ShowRoundedCorner="true" ContentType="TextAndImage" PrefixIcon="e-save" /> 
            </DialogContent> 
        </ej:Dialog> 
    </div> 
    <script> 
        function Save() { 
            var obj = $("#MainContent_Grid").ejGrid("instance"); 
            //Manually update the Grid data 
            var data = { OrderID: Math.ceil(Math.random() * 1000), CustomerID: "VINET" + Math.ceil(Math.random() * 10) }; 
            obj.addRecord(data);//Grid method 
            $(".dlg").hide(); 
            $("#MainContent_dialog").ejDialog("close"); 
        } 
        function openDialog() { 
            $(".dlg").show() 
            $("#MainContent_dialog").ejDialog("open"); 
        } 
    </script> 


Note: Since you haven’t provide information on the data that has to inserted in Grid, we have used a dynamic data to be inserted in a Grid.  

If we misunderstood your query, please provide the following information to analyze the issue.  

1)      In the code example, you have sent the ajax post to insert a record. How you are getting the inserted record in the button click? 
2)      Explain the scenario to insert the record into the Grid? 

We have also prepared a sample that can be downloaded from the location. 


Refer to the following KB for server-side api operations. 


Regards, 
Seeni Sakthi Kumar S. 



PR Pratura July 5, 2016 02:17 PM UTC

Thank you.
I would like to use CRUD methods with WebMethodAdaptor.

I have put the DataManager URL to call the DataSource function just like in your example

 <DataManager URL="Default.aspx/DataSource" Adaptor="WebMethodAdaptor" />

I am getting the data from a stored procedure to datatable and converting it with .AsEnumerable()

Public Shared Function DataSource(value As Syncfusion.JavaScript.DataManager) As Object

       Dim db As New Db

        Dim Data As IEnumerable = db.getData("GH_HUO_Uninsured_Vehicles_Select").AsEnumerable()

        Dim count As Integer = Data.AsQueryable().Count()

        Dim operation As New Syncfusion.JavaScript.DataSources.DataOperations()

        Data = operation.Execute(Data, value)

        Return New With {

        Key .result = Data,

        Key .count = count

        }

End Function

On debug i can see that the data is populated correctly with both .count and .data but the grid just shows the loading icon spinning indefinitely and does not populate.

See the attached pic please.

If we misunderstood your query, please provide the following information to analyze the issue.  

1)      In the code example, you have sent the ajax post to insert a record. How you are getting the inserted record in the button click? 

2)      Explain the scenario to insert the record into the Grid?

1) I don't understand the sentence: How you are getting the inserted record in the button click? 

It's all in my previous posts :-) Through a Save function 

2)  When populating the controls from the Dialog the Save button executes AJAX calling Save method which inserts a record to DB 

After that the grid needs to be refreshed, but i am willing to use CRUD if you could help me solve this.

 Public Sub ExecuteStoredProcedure(command As SqlCommand)

        Dim connection As New SqlConnection(conn)

        connection.Open()

        command.Connection = connection

        command.CommandType = CommandType.StoredProcedure

        command.ExecuteNonQuery()

        connection.Close()

    End Sub


Attachment: grid_511a8e29.7z


PK Prasanna Kumar Viswanathan Syncfusion Team July 6, 2016 10:51 AM UTC

Hi Pratura, 

Thanks for the update. 

Before proceed with your requirement we need the following details, 
 
1. Did you face any console error while run the sample? 
 
2. Provide the stackrace of an exception in the console page, it will help us to find out cause of an issue. 
 
3. Essential Studio Version details.  
 
4. If possible, share the sample or replicate the issue in the attached sample. 
 
Regards, 
Prasanna Kumar N.S.V 
 
 
 


Loader.
Up arrow icon