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

Rebind Grid after Ajax Request

4 Answers 324 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Marc
Top achievements
Rank 1
Marc asked on 16 Feb 2013, 02:38 PM
Hi,

I have a grid with some columns being updated by a stored procedure from the code behind when a user clicks a button. This button executes an Ajaxrequest on the client to fire the stored procedure handled in RadAjaxManager1.AjaxRequest code behind, and the database is updated as expected. The problem is now with the displayed grid because it's not being refreshed with the latest changes...

Javascript code:
function buttonResetClick(sender, args) {
if .... some conditions... {
radconfirm("Changing the currency will reset all product prices. Continue?", aspButtonCallbackFn, 380, 110, null, "Confirm price reset"); return false;
}
function aspButtonCallbackFn(arg) { if (arg) { refreshGrid(orderCreated.value, actualCurrency.get_selectedItem().get_value()); } }
}
 
function refreshGrid(arg, currency) {
            $find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("ResetAndRebind," + arg + "," + currency);
// Try to force a Postback, grid is not updated
//           __doPostBack("<%= ProcessBtn.UniqueID%>", "");
        }

ASP.NET
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                <UpdatedControls><telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" /></UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
     
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
 
<telerik:RadButton ID="ProcessBtn" OnClientClicked="buttonResetClick" AutoPostBack="false" runat="server" Text="Process Currency" CausesValidation="true" ValidationGroup="MainCurdata" />
 
<telerik:RadGrid ID="RadGrid1" runat="server" CellSpacing="0" GridLines="None" AllowAutomaticInserts="True" AllowAutomaticUpdates="True" AllowAutomaticDeletes="False" ondeletecommand="RadGrid1_DeleteCommand" AllowMultiRowEdit="True" Visible="false">
        <ClientSettings ClientEvents-OnRowCreated="countRows"><ClientEvents OnRowClick="RowClick" OnRowDblClick="RowDblClick" OnGridCreated="GridCreated" OnCommand="GridCommand"></ClientEvents></ClientSettings>
        <MasterTableView CommandItemDisplay="Top" AutoGenerateColumns="false" EditMode="InPlace" DataKeyNames="Id,OrderId">
<Columns> LIST </Columns>
</MasterTableView>
            <FilterMenu EnableImageSprites="False" />
</telerik:RadGrid>

Code Behind:
The rebind command doesn't update the view...
Protected Sub RadAjaxManager1_AjaxRequest(sender As Object, e As AjaxRequestEventArgs) Handles RadAjaxManager1.AjaxRequest
        Dim argument As String = e.Argument
        Dim stringArray As [String]() = argument.Split(",".ToCharArray())
        Dim orderId As Integer = stringArray(1)
        If stringArray(0) = "ResetAndRebind" Then
 
            Using Context As New StocksEntities()
                Context.currencyResetFields(orderId)
STORED PROCEDURE UPDATE
                Context.SaveChanges()
            End Using
            RadGrid1.Rebind()
        End If
    End Sub

I also tried another approach within the JS, forcing a postback (__doPostBack("<%= ProcessBtn.UniqueID%>", "");) after the ajaxrequest, but unfortunately the postback is conducted before ajax ends the request...

I checked this similar threat http://www.telerik.com/community/forums/aspnet-ajax/grid/rebind-a-grid-with-an-ajaxrequest.aspx, experiencing the same problem but the answer does not help me. All I need is an ability to rebind the bind after the ajaxrequest.

Any solution?

Thanks!

4 Answers, 1 is accepted

Sort by
0
Jayesh Goyani
Top achievements
Rank 2
answered on 18 Feb 2013, 08:18 AM
Hello,

Your code seems correct.

Please provide your whole page code or submit your code using support ticket.

Note :

If you want to use Rebind method then you have to follow below binding method.

1. DataSourceID
2. NeedDataSource event (http://demos.telerik.com/aspnet-ajax/grid/examples/programming/needdatasource/defaultcs.aspx)

Thanks,
Jayesh Goyani
0
Marc
Top achievements
Rank 1
answered on 19 Feb 2013, 12:15 AM
Hi Jayesh,

Thanks for your quick reply!
I changed, as suggested, the binding to use NeedDataSource event but unfortunately the grid is not updated. I forgot to specify that the grid is inside a TabStrip.

Here is the relevant code:
<script type="text/javascript">
        var currentLoadingPanel = null;
        var currentUpdatedControl = null;
        function RequestStart(sender, args) {
            currentLoadingPanel = $find("<%= RadAjaxLoadingPanel1.ClientID%>"); currentUpdatedControl = "<%= Panel1.ClientID %>"; currentLoadingPanel.show(currentUpdatedControl);
        }
        function updateData() {__doPostBack("<%= ProcessBtn.UniqueID%>", ""); }
        function refreshGrid(arg, currency) {
            $find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("ResetAndRebind," + arg + "," + currency);
            __doPostBack("<%= ProcessBtn.UniqueID%>", "");  // Try to force a Postback, grid is not updated
        }
    var hasChanges, inputs, dropdowns, editedRow;
    function RowClick(sender, eventArgs) {
        if (editedRow && hasChanges) { hasChanges = false; if (confirm("Update changes?")) { $find("<%= RadGrid1.ClientID %>").get_masterTableView().updateItem(editedRow); } }
    }
 
        function RowDblClick(sender, eventArgs) { editedRow = eventArgs.get_itemIndexHierarchical(); $find("<%= RadGrid1.ClientID %>").get_masterTableView().editItem(editedRow); }
            function GridCommand(sender, args) { if (args.get_commandName() != "Edit") { editedRow = null; } }
            function GridCreated(sender, eventArgs) {
                var gridElement = sender.get_element();
                var elementsToUse = [];
                inputs = gridElement.getElementsByTagName("input");
                for (var i = 0; i < inputs.length; i++) {
                    var lowerType = inputs[i].type.toLowerCase();
                    if (lowerType == "hidden" || lowerType == "button") { continue; }
                    if (inputs[i].id.indexOf("PageSizeComboBox") == -1 && inputs[i].type.toLowerCase() != "checkbox") { Array.add(elementsToUse, inputs[i]); }
                    inputs[i].onchange = TrackChanges;
                }
                dropdowns = gridElement.getElementsByTagName("select");
                for (var i = 0; i < dropdowns.length; i++) { dropdowns[i].onchange = TrackChanges; }
                setTimeout(function () { if (elementsToUse[0]) elementsToUse[0].focus(); }, 100);
            }
            function TrackChanges(e) { hasChanges = true; }
 
        function CheckUpdates(sender, args) {
            var initialCurrency = document.getElementById("<%=CurrencyHidden.ClientID%>");
            var actualCurrency = $find('<%=RadComboBoxCurrency.ClientID%>');
            var orderCreated = document.getElementById("<%=GeneratedOrder.ClientID%>");
            function aspButtonCallbackFn(arg) { if (arg) { refreshGrid(orderCreated.value, actualCurrency.get_selectedItem().get_value()); } }
 
            if (orderCreated.value != "") {
                var grid = $find("<%=RadGrid1.ClientID %>");
                var MasterTable = grid.get_masterTableView();
                var Rows = MasterTable.get_dataItems();
 
                if (Rows.length > 0) {
                    if (initialCurrency.value != actualCurrency.get_selectedItem().get_value()) {
                        radconfirm("Changing the currency will reset all product prices. Continue?", aspButtonCallbackFn, 380, 110, null, "Confirm price reset"); return false;
                    } else { updateData(); }
                } else { updateData(); }
                 
            } else { updateData(); }
        }
 
</script>
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
     
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
    <telerik:RadTabStrip ID="RadTabStrip1" runat="server" MultiPageID="RadMultiPage1" Skin="Office2010Silver" OnClientTabSelecting="onTabSelecting">
        <Tabs>
            <telerik:RadTab runat="server" Text="Basic" Selected="true" />
        </Tabs>
    </telerik:RadTabStrip>
 
        <telerik:RadMultiPage runat="server" ID="RadMultiPage1" SelectedIndex="0" CssClass="multiPage">
             
             
            <telerik:RadPageView runat="server" ID="RadPageView1">
<!-- PRODUCT TABLE -->
<asp:PlaceHolder ID="ProductEntryPH" runat="server" Visible="true">
    <telerik:RadGrid ID="RadGrid1" runat="server" CellSpacing="0" GridLines="None" AllowAutomaticInserts="True" AllowAutomaticUpdates="True" AllowAutomaticDeletes="False" ondeletecommand="RadGrid1_DeleteCommand" Height="600px" Width="100%" ShowFooter="true" AllowMultiRowEdit="True" Visible="false">
        <MasterTableView CommandItemDisplay="Top" AutoGenerateColumns="false" EditMode="InPlace" DataKeyNames="Id,OrderId,ProductVariantId">
            <Columns>
                <telerik:GridBoundColumn DataField="Id" DataType="System.Int32" FilterControlAltText="Filter Id column" HeaderText="Id" ReadOnly="True" SortExpression="Id" UniqueName="Id" Visible="false"/>
                <telerik:GridBoundColumn DataField="OrderId" DataType="System.Int32" FilterControlAltText="Filter OrderId column" HeaderText="Order" SortExpression="OrderId" UniqueName="OrderId" Visible="false" ReadOnly="true" />
                <telerik:GridDropDownColumn DataSourceID="SqlDSProductList" ListTextField="Name" ListValueField="Id" HeaderStyle-Width="400px" UniqueName="VariantId" SortExpression="Name" HeaderText="Product" DataField="ProductVariantId" DropDownControlType="RadComboBox" AllowAutomaticLoadOnDemand="true" AllowVirtualScrolling="true" ShowMoreResultsBox="true" ItemsPerRequest="25"></telerik:GridDropDownColumn>
                <telerik:GridTemplateColumn UniqueName="Sku" ReadOnly="True" HeaderText="Sku">
                    <ItemTemplate><asp:Label runat="server" ID="SkuId" ViewStateMode="Enabled"></asp:Label></ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridNumericColumn DataField="Quantity" DataType="System.Int32" FilterControlAltText="Filter Quantity column" HeaderText="Qty" SortExpression="Quantity" UniqueName="Quantity" DefaultInsertValue="10" EmptyDataText="0" FooterText="Items: " Aggregate="Sum" FooterAggregateFormatString="" />
                <telerik:GridNumericColumn DataField="ProductCost" DataType="System.Decimal" FilterControlAltText="Filter ProductCost column" HeaderText="Cost" SortExpression="ProductCost" UniqueName="ProductCost" DecimalDigits="4" NumericType="Currency" DefaultInsertValue="0" EmptyDataText="0" FooterText="Total:" Aggregate="Sum" FooterAggregateFormatString="{0:C}" />
                <telerik:GridNumericColumn DataField="ProductCostCurrency" DataType="System.Decimal" FilterControlAltText="Filter ProductCost column" HeaderText="Cost Currency" SortExpression="ProductCostCurrency" UniqueName="ProductCostCurrency" DecimalDigits="4" NumericType="Currency" DefaultInsertValue="0" EmptyDataText="0" FooterText="Total:" Aggregate="Sum" FooterAggregateFormatString="{0:C}" />
                <telerik:GridCalculatedColumn HeaderText="Net Amount" UniqueName="TotalPrice" DataType="System.Decimal" DataFields="Quantity, ProductCost, ProductCostCurrency" Expression="{0}*({1}+{2})" FooterText="Total : " Aggregate="Sum" FooterAggregateFormatString="{0:C}" DataFormatString="{0:C}" />
                <telerik:GridNumericColumn DataField="ProductCostShipping" DataType="System.Decimal" FilterControlAltText="Filter ProductCostShipping column" HeaderText="Cost Shipping" SortExpression="ProductCostShipping" UniqueName="ProductCostShipping" DecimalDigits="4" NumericType="Currency" DefaultInsertValue="0" EmptyDataText="0" FooterText="" Aggregate="Sum" FooterAggregateFormatString="{0:C}" Visible="false" />
                <telerik:GridNumericColumn DataField="ProductCostCustoms" DataType="System.Decimal" FilterControlAltText="Filter ProductCostCustoms column" HeaderText="Cost Customs" SortExpression="ProductCostCustoms" UniqueName="ProductCostCustoms" DecimalDigits="4" NumericType="Currency" DefaultInsertValue="0" EmptyDataText="0" FooterText="" Aggregate="Sum" FooterAggregateFormatString="{0:C}" Visible="false" />
                <telerik:GridNumericColumn DataField="ProductCostFinancial" DataType="System.Decimal" FilterControlAltText="Filter ProductCostFinancial column" HeaderText="Cost Financial" SortExpression="ProductCostFinancial" UniqueName="ProductCostFinancial" DecimalDigits="4" NumericType="Currency" DefaultInsertValue="0" EmptyDataText="0" FooterText="" Aggregate="Sum" FooterAggregateFormatString="{0:C}" Visible="false" />
                <telerik:GridNumericColumn DataField="TotalProductCost" DataType="System.Decimal" FilterControlAltText="Filter TotalProductCost column" HeaderText="Total Cost" SortExpression="TotalProductCost" UniqueName="TotalProductCost" DecimalDigits="4" NumericType="Currency" DefaultInsertValue="0" EmptyDataText="0" FooterText="" Aggregate="Sum" FooterAggregateFormatString="{0:C}" Visible="false" />
                <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
                <telerik:GridButtonColumn Text="Delete" CommandName="Delete" ButtonType="ImageButton" />
            </Columns>
            </MasterTableView>
            <ClientSettings><ClientEvents OnRowClick="RowClick" OnRowDblClick="RowDblClick"></ClientEvents></ClientSettings>
            <FilterMenu EnableImageSprites="False" />
    </telerik:RadGrid>
</asp:PlaceHolder>
</telerik:RadPageView>
</telerik:RadMultiPage>

Code Behind:
Private Sub RadGrid1_NeedDataSource(sender As Object, e As GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
    RadGrid1.DataSourceID = "EntityDataSource2"
End Sub
 
Private Sub RadGrid1_ItemCreated(sender As Object, e As GridItemEventArgs) Handles RadGrid1.ItemCreated
    If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
        Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
        Dim dropDownEditor As GridDropDownListColumnEditor = DirectCast(item.EditManager.GetColumnEditor("VariantId"), GridDropDownListColumnEditor)
        dropDownEditor.ComboBoxControl.Width = Unit.Pixel(395)
        dropDownEditor.ComboBoxControl.Filter = RadComboBoxFilter.Contains
    End If
End Sub
 
Private Sub RadGrid1_ItemDataBound(sender As Object, e As GridItemEventArgs) Handles RadGrid1.ItemDataBound
    Dim nmc As RadNumericTextBox
    If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
        Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
        Dim dropDownEditor As GridDropDownListColumnEditor = DirectCast(item.EditManager.GetColumnEditor("VariantId"), GridDropDownListColumnEditor)
        dropDownEditor.ComboBoxControl.Width = Unit.Pixel(395)
        nmc = DirectCast(item("Quantity").Controls(0), RadNumericTextBox)
        nmc.Width = Unit.Pixel(40)
 
    ElseIf TypeOf e.Item Is GridDataItem AndAlso Not e.Item.IsInEditMode Then
        Dim item As GridDataItem = TryCast(e.Item, GridDataItem)
        Dim label As Label = TryCast(item.FindControl("SkuId"), Label)
        If CInt(item.GetDataKeyValue("ProductVariantId")) > 0 Then label.Text = FindSku(item.GetDataKeyValue("ProductVariantId"))
    End If
End Sub

Thanks for your help!
0
Accepted
Andrey
Telerik team
answered on 21 Feb 2013, 06:59 AM
Hi,

Since the RadGrid is located inside RadTabStrip and RadMultiPage you should Ajax-ify these control instead of RadGrid. Try to modify your settings as follows:

<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
    <AjaxSettings>
        <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
            <UpdatedControls>
                <telerik:AjaxUpdatedControl ControlID="RadTabStrip1" LoadingPanelID="RadAjaxLoadingPanel1" />
                <telerik:AjaxUpdatedControl ControlID="RadMultiPage1" LoadingPanelID="RadAjaxLoadingPanel1" />
            </UpdatedControls>
        </telerik:AjaxSetting>
        <telerik:AjaxSetting AjaxControlID="RadMultiPage1">
            <UpdatedControls>
                <telerik:AjaxUpdatedControl ControlID="RadMultiPage1" LoadingPanelID="RadAjaxLoadingPanel1" />
            </UpdatedControls>
        </telerik:AjaxSetting>
    </AjaxSettings>
</telerik:RadAjaxManager>

and you should not have problems.

Kind regards,
Andrey
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Marc
Top achievements
Rank 1
answered on 21 Feb 2013, 07:33 AM
You are right! It works perfectly. Thank you so much.
Tags
Grid
Asked by
Marc
Top achievements
Rank 1
Answers by
Jayesh Goyani
Top achievements
Rank 2
Marc
Top achievements
Rank 1
Andrey
Telerik team
Share this question
or