Calling the ItemCommand Handler from JavaScript

26 posts, 0 answers
  1. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 28 Jan 2009 Link to this post

    I am trying to get a confirmation dialog working when the user hit's "Update" button in a MasterEditTemplateForm template of a RadGrid.  The scenerio is working fine in all other respects.  I have followed the appropriate links, have the JavaScript in an external file and a container div working correctly that displays the dialog to the user. 

    I can step into the JavaScript code and verify that OpenConfirm() dialog shows the correct message to the user, and can also verify that the return result is true or false based on the Ok or Cancel buttons clicked.

    How can I fire the Grid's ItemCommand handler if the result of the dialog was yes?

    function confirmCallBackFn(arg) {  
         return arg;  

    function OpenConfirm(customTitle) {  
        return radconfirm('<h3><span style="color: #333399;">' + customTitle + '?</span></h3>', confirmCallBackFn, 330, 100, customTitle);  
        return false;  

    <asp:Button ID="btnSave" runat="server" CommandArgument="PerformInsert" CssClass="ButtonStyle"   
                                                                                            Text="Insert" CommandName="PerformInsert" OnClientClick="javascript: if (OpenConfirm('Save Food Menu Item Editing')) {return true;}else{return false;}" /> 

    The ItemCommand handler would normally validate the data entry and then call a boolean function to either insert or update data.  The result of that function closes or does not close the MasterEditTemplate form. 

    I need to integrate the confirmation dialog into the project.  Any suggestions would be appreciated.

    Thanks
  2. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 28 Jan 2009 Link to this post

    Hello Reid,

    You can invoke the fireCommand method to trigger the corresponding command for the grid as shown below:
    js:
     function confirmCallBackFn(arg) 
        {       
          if(arg==true) 
          {         
               var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView(); 
               masterTable.fireCommand("PerformInsert",""); 
          } 
        }  

    cs:
    protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e) 
        { 
            if (e.CommandName == RadGrid.PerformInsertCommandName) 
            { 
     
            } 
        } 

    Thanks
    Princy.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 29 Jan 2009 Link to this post

    Hi Princy, this looks like it would work but makes no distinction with respect to whether the Grid is in Edit or Insert Mode, in other words should the confirmCallBackFn() use "PerformInsert" or "Update"?  Is there another built in JavaScript method to establish this?
  5. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 29 Jan 2009 Link to this post

    Also Princy, the line below throws an exception in the JavaScript:

    var masterTable = $find("<%= grdFoodMenuListing.ClientID %>").get_masterTableView(); 

    the identifier above passed to the $find() function is always null.
  6. Daniel
    Admin
    Daniel avatar
    4943 posts

    Posted 30 Jan 2009 Link to this post

    Hello Reid,

    Try the following approach:
    <script type="text/javascript" language="javascript"
        var radGrid; 
        function GridCreated(sender, args) 
        { radGrid = sender; } 
     
        function confirmCallBackFn(arg) 
        { 
            if (arg == true
                radGrid.get_masterTableView().fireCommand("PerformInsert"""); 
        }  
    </script> 

    <ClientEvents OnGridCreated="GridCreated" /> 

    Regards,
    Daniel
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  7. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 30 Jan 2009 Link to this post

    Hello Daniel,

    Thanks for the reply.  I do not see how to address the issue of determining if the grid is in INSERT or UPDATE mode so that I can fire PerformInsert or Update.
  8. Yavor
    Admin
    Yavor avatar
    11 posts

    Posted 30 Jan 2009 Link to this post

    Hi Reid,

    Attached to this message, is a small example, which demonstrates how to detect insert/edit mode for the control.
    I hope it helps.

    Regards,
    Yavor
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  9. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 31 Jan 2009 Link to this post

    Hello Yavor,

    The attachment uses LINQ to load data from a APP_DATA folder demonstrating the Telerik SessionDataSource class (handy, thank you) but I do not see anything related to detecting insert/edit mode, forgive me if I am missing something.
  10. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 31 Jan 2009 Link to this post

    With the code in place below I can say the following is working :

    • The "Update" button in the MasterEditTemplate of the RadGrid when clicked shows the RadWindow confirmation dialog in the div to the user and the correct response via the OpenConfirm() function is passed to the argument of the confirmCallBackFn() function.
    • The radGrid variable is not null and the fireCommand functions can be called.
    • The case below that fires the "Update", indeed fires the ItemCommandHandler with the correct "RadGrid.UpdateCommandName" constant.

    Questions

    1. ItemIndex parameter  As you can see below I am passing the ItemIndex arg as "0" (to test)
    2. Determining Insert or Update state when firing the fireCommand() function. Still no way to determine what state the grid is in, Edit or Insert) I do not want to expand the JS to include an additional param for the state (actually just the button caption) but would rather abstract that processing to the JS to inherently cover future scenarios.

    JS:
    var radGrid;  
    function GridCreated(sender, args) { radGrid = sender; }  
     
     
    function confirmCallBackFn(arg) {  
        if (radGrid != null) {  
            if (arg == true)  
                radGrid.get_masterTableView().fireCommand("Update", 0);  
        }    
     
    function OpenConfirm(customTitle) {  
        return radconfirm('<h3><span style="color: #333399;">' + customTitle + '?</span></h3>', confirmCallBackFn, 330, 100, customTitle);  
        return false;  

    ASPX: (Note, my SetCommandHandlerText() method below sets the button's caption and commandtype on the web page's PageLoad() to let the button work for both Insert and Update)

    <asp:Button ID="btnSave" runat="server" CommandArgument="PerformInsert" CssClass="ButtonStyle"
     Text="Insert" CommandName="PerformInsert" OnClientClick="javascript: 
       if (OpenConfirm('Save Food Menu Item Editing')) {return true;}else{return false;}"
     /> 

     

     

     private void SetCommandHandlerContext()  
        {  
            if ( Session[SessionEnumeratedKeys.SessionKey_DataActionMode] != null )  
            {  
                string dataActionModeStr = Session[SessionEnumeratedKeys.SessionKey_DataActionMode].ToString();  
                Enums.DataActionMode dataActionMode = (Enums.DataActionMode) Enum.Parse(typeof(Enums.DataActionMode), dataActionModeStr);  
     
                Button saveBtn = (Button) HTMLUtility.FindControlRecursive(this.Master, "btnSave");  
                if ( saveBtn != null )  
                {  
                    switch ( dataActionMode )  
                    {  
                        case Enums.DataActionMode.Insert:  
                            {  
                                saveBtn.Text = "Insert";  
                                saveBtn.ToolTip = "Insert new Food Menu Item";  
                                saveBtn.CommandName = RadGrid.PerformInsertCommandName;  
                                saveBtn.CommandArgument = RadGrid.PerformInsertCommandName;  
                                break;  
                            }  
                        case Enums.DataActionMode.Edit:  
                            {  
                                saveBtn.Text = "Update";  
                                saveBtn.ToolTip = "Update Food Menu Item";  
                                saveBtn.CommandName = RadGrid.UpdateCommandName;  
                                saveBtn.CommandArgument = RadGrid.UpdateCommandName;  
                                break;  
                            }  
             }  
           }  
       }  

  11. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 01 Feb 2009 Link to this post

    A followup on my last post.

    Waiting for the Telerik team to return Monday I have been investigating and experimenting.  My solution is working but the ItemCommand always contains the MasterTable as the e.Item.OwnerTableView.Name coming into the event handler in the code behind.



    I created a new JavaScript function that the button object in the markup below can call passing in itself as an additional parameter.  This way I can determine if the record is in "Update" or "Insert" mode. ( again I would prefer not to do it this way )

    ASPX:

    asp:Button 
    ID="btnSave" runat="server" CommandArgument="PerformInsert" CssClass="ButtonStyle" Text="Insert"   
    CommandName="PerformInsert" OnClientClick="javascript: if (confirmAndFireItemCommand('Save Food Menu Item Editing', this)) {return true;}else{return false;}" /> 

    JS:
    var activeCommandButton; 

    JS:
    function confirmAndFireItemCommand(customTitle, button) {  
        activeCommandButton = button;  
        return radconfirm('<h3><span style="color: #333399;">' +  
          customTitle + '?</span></h3>', confirmCallBackFn, 330, 100, customTitle);  

    JS:

    function
     confirmCallBackFn(arg, button) {  
        if (radGrid != null) {  
            if (arg == true) {  
     
                if (activeCommandButton.value == 'Update') {  
                    for (i = 0; i < radGrid.get_detailTables().length; i++) {  
                        var detailTable = radGrid.get_detailTables()[i];  
                        var tableName = detailTable.get_name();  
                        if (tableName == 'FoodMenuItems') {  
                            detailTable.fireCommand("Update", 0);  
                            break;  
                        }  
                    }  
                }  
            }  
        }  
        return false;  

    Again, after the ItemCommand handler is fired the ItemCommand handler sees it as the outer MasterTableView, not the nested GridTableView detail table that is the record being edited.
  12. Yavor
    Admin
    Yavor avatar
    11 posts

    Posted 02 Feb 2009 Link to this post

    Hello Reid,

    I double-tested the setup - below is the code which detects the insert/edit mode respectively:

      <script type="text/javascript">  
                          
                        function gridCreated(sender, args)  
                        {  
                        var RadGrid = $find("<%=Grid1.ClientID %>");  
                        alert("Inserting:" + RadGrid.get_masterTableView().get_isItemInserted());  
                        alert("editItems:" + RadGrid._editIndexes.length);  
                        }  
                    
                </script> 

    this is ran in the onGridCreated client side handler.
    Let me know if I am leaving something out.

    Best wishes,
    Yavor
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  13. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 02 Feb 2009 Link to this post

    Hello again,

    I have, and have had it configured as you mention.  I tried using your JS code in my external .js file and at no time does the following line return a valid instance of the grid :

    <script type="text/javascript">     
                             
       function gridCreated(sender, args)     
        {     
          var RadGrid = $find("<%=grdFoodMenuListing.ClientID %>");    <<------ 
          alert("Inserting:" + RadGrid.get_masterTableView().get_isItemInserted());     
          alert("editItems:" + RadGrid._editIndexes.length);     
        } 
                      
     </script>    
     

    If I place this code inside the ContentPlaceHolder of the template I get an exception :

    [Message]
    The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

    [Stack]
    at System.Web.UI.ControlCollection.AddAt(Int32 index, Control child)
    at Telerik.Web.UI.RadAjaxControl.MoveUpdatePanel(Control initiator, Control updated)

    ASPX:
    <ClientSettings> 
       <ClientEvents OnGridCreated="GridCreated"/>  
    </ClientSettings 

    But this works if I place it in the external .js file:

    function GridCreated(sender, args) {     
        radGrid = sender;         
    }    
     

    And as a result the "confirmCallBackFn" callback has access to it when the radconfirm() function is called. 

    So my questions are :
    1. Do you know why the page cannot find the grid using "$find"?
    2. Why after firing the JavaScript function "fireCommand()" on the *detail* table does the ItemCommand always contains the MasterTable as the e.Item.OwnerTableView.Name coming into the event handler in the code behind instead of the nested detail table's name?

    Please address the second question first.

    Thank you

  14. Yavor
    Admin
    Yavor avatar
    11 posts

    Posted 02 Feb 2009 Link to this post

    Hello Reid,

    To see more information on why this exception is raised, please refer to the following article.
    I hope it helps.

    Greetings,
    Yavor
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  15. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 02 Feb 2009 Link to this post

    Ok, thanks for that, now the code placed in the ASPX page works, how much I benefit from that over everything in the external .js file I do not know.   I do not need to include the button now to query the edit state of the grid.

    But again, the problem is as in my last post ....  Please answer this question for the 3rd time in this forum, why is the ItemCommand handler in the CS code seeing the e.CommandName as the MasterTableView and *NOT* the embedded detail table? 
  16. Yavor
    Admin
    Yavor avatar
    11 posts

    Posted 05 Feb 2009 Link to this post

    Hi Reid,

    Based on the supplied information, it is hard to determine what is causing the issue with the command name. To further investigate it, please open a formal support ticket, and send us a small project, demonstrating your setup and code logic.
    We will debug it locally, and get back to you with additional information.

    Sincerely yours,
    Yavor
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  17. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 05 Feb 2009 Link to this post

    Yavor,  thank you for following up on this issue.  I can push a build to my server to provide more of a demonstration once I get this issue resolved. 

    I have created a support ticket and copied this thread's URL into it for reference.  Once resolved I will follow up and post the resolve here in this thread for others.

    Thanks
  18. Reid
    Reid avatar
    317 posts
    Member since:
    Oct 2008

    Posted 07 Feb 2009 Link to this post

    I wanted to follow up and complete this thread with the details of what was needed to get this going.

    First of all here is the JavaScript code that fires the command against the correct GridTableView :

    function confirmCallBackFn(arg) {  
        if (arg == true) {        
            var editIndexCount = radGrid._editIndexes.length;     
            var detailTablesArray = radGrid.get_detailTables();  
            var detailTable = detailTablesArray[3];  
              
            // We are either in Update or Insert mode  
            if (editIndexCount > 0)  
            {  
                detailTable.fireCommand("UpdateFoodMenuItem");            
            }  
            else 
            {  
                detailTable.fireCommand("InsertFoodMenuItem");     
            }         
        }  

    Now why that works and the code in the above post (Feb 1st) did not, where I iterated though the detail tables to fire the event I am not sure. In my previous post the code behind handler was only being called for the root or primary GridTableView (MasterTableView).  Using the JavaScript above it works with the understanding that you have to use a "Custom" parameter, in my case "UpdateFoodMenuItem".

    While I am thankful for the support I got from Telerik on this, I would like to format a generic JS script to detect the active GridTableView.  As you can see the index of the GridTableView is hard coded, I would make sense to abstract that from the call.

    Reid
  19. Amarendra Parab
    Amarendra Parab avatar
    5 posts
    Member since:
    Jan 2010

    Posted 16 Feb 2010 Link to this post

    // JScript File  
        function confirmCallBackFn(arg) {  
            if (arg == true) {  
                //alert("in confirmCallBackFn function");  
                var masterTable = $find("<%= rdgEduDetail.ClientID %>").get_masterTableView();  
                masterTable.fireCommand("UpdateAll", "");  
            }  
        }  
     
        function confirmEducationSave() {  
            confirmCallBackFn(confirm("Do you want to save."));  
        }   
     
     
    The confirmEducationSave() is called in the onClick of the following button

    <div id="divUpdateCancel" runat="server" visible="false">  
                <asp:Button runat="server"  ID="UpdateAll" Text="Update All"  CommandName="UpdateAll" /> 
                <asp:Button runat="server" ID="CancelAll" Text="Cancel All" CommandName="CancelAll" /> 
            </div> 
    by adding a attribute in following way

    UpdateAll.Attributes.Add("onclick", "return confirmEducationSave();"); 

    When i click the UpdateAll button i do get the "Do you want to save." confirm message and i also check that it does go inside the if condition in "confirmCallBackFn(arg)" button for some reason it doesnt call the ItemCommand event handler of "rdgEduDetail".
  20. Amarendra Parab
    Amarendra Parab avatar
    5 posts
    Member since:
    Jan 2010

    Posted 17 Feb 2010 Link to this post

    i was able to get the Itemcommand to be called from client side after modifying the Javascript function as mentioned in this article and added the client event element.

    The only issue remains is that it isnt going back to the view mode. It stays in the edit mode
  21. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 18 Feb 2010 Link to this post

    Hello Amarendra,

    Try clearing the edited items using the below code for instance. Note that you will need to rebind the grid afterwards:

    RadGrid1.EditIndexes.Clear();
    RadGrid1.Rebind();


    Greetings,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  22. Amarendra Parab
    Amarendra Parab avatar
    5 posts
    Member since:
    Jan 2010

    Posted 18 Feb 2010 Link to this post

    Hi Iana,

    I have a Support ID:282304 in which speaks about the same issue but with more information and have also replied on what you had suggested to that ticket, that was prior to this reply on this thread. Please refer that support ticket and go through my reply  where i have added more information of what is exactly happening.

    As far as your reply for this thread goes, i have already done e.Edit = false( e is the GridCommandEventArgs of ItemCommand event) which is equivalent to removing the item from the EditIndexes.Clear() method. Also after doing e.Edit = False i am doing a Rebind() on the RADGrid.


    I tried the suggestion you gave but it is not working.

    Please give you suggestion on the Support id : 282304, so that we have only one follow up on this issue.

    Thanks,

    Amarendra

  23. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 18 Feb 2010 Link to this post

    Hello Amarendra,

    Thank you for opening a support ticket. I will check it out and write you back there.

    Greetings,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  24. RBarnes
    RBarnes avatar
    46 posts
    Member since:
    Oct 2012

    Posted 27 Jan in reply to Reid Link to this post

    I know this is an old thread, but was/is there a resolve for this issue discussed here?

    I was able to add a custom command and work around the issue, but the below is still an issue with firecommand on a DetailTable is issued.

     

     

     Why after firing the JavaScript function "fireCommand()" on the *detail* table does the ItemCommand always contains the MasterTable as the e.Item.OwnerTableView.Name coming into the event handler in the code behind instead of the nested detail table's name?

  25. Eyup
    Admin
    Eyup avatar
    3007 posts

    Posted 01 Feb Link to this post

    Hi,

    Make sure you are firing the command with client-side object of the corresponding GridTableView:
    http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/client-side-programming/gridtableview-object/methods/firecommand

    If the behavior remains, you can pass a custom argument as the second parameter and use it on the code-behind to get the name of the real table view.

    Regards,
    Eyup
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  26. RBarnes
    RBarnes avatar
    46 posts
    Member since:
    Oct 2012

    Posted 01 Feb in reply to Eyup Link to this post

     My JS.

     The JS is attached to the CloseEvent of FileExplorer.

    var grid = $find("<%= rgWorkflow.ClientID%>");
    var detailTable = grid.get_detailTables()[0];
    detailTable.fireCommand("Update",3,0); //This seems to always be our tvMasterTable versus tvDetailTable like we need using a custom command

     

     Partial ASPX. lnkAttachments CommandName"Edit", which is in the DetailTable

    Partial aspx
     
     <telerik:RadGrid ID="rgWorkflow" runat="server" AllowSorting="True" GridLines="None" ItemStyle-Font-Size="8pt" MasterTableView-ShowFooter="true"
                        EnableHierarchyExpandAll="true"
                        AutoGenerateColumns="False" HeaderStyle-Font-Size="8pt" Visible="True" Width="980px">
                        <MasterTableView Name="tvMasterTable" DataKeyNames="sprw_ProjectHeaderItemsID, sprw_SPRWorkflowID,sprw_SPRWorkflowLocationID,sprw_EndDateTime"
                            CommandItemDisplay="Top" PageSize="50" EditMode="PopUp">
                            <DetailTables>
                                <telerik:GridTableView EnableHierarchyExpandAll="true" Name="tvDetails"
                                    DataKeyNames="sprwc_SPRWorkflowID, sprwc_SPRWorkflowCommentsID, sprwc_UsersID" runat="server"
                                    CommandItemDisplay="Bottom" CssClass="ReplyPadding"
                                    EditMode="PopUp" AllowAutomaticDeletes="False" AllowAutomaticInserts="False" AllowAutomaticUpdates="False">
                                    <ParentTableRelation>
                                        <telerik:GridRelationFields DetailKeyField="sprwc_SPRWorkflowID" MasterKeyField="sprw_SPRWorkflowID" />
                                    </ParentTableRelation>
                                    <Columns>
                                        <telerik:GridBoundColumn DataField="UserFullName" UniqueName="UserFullName" HeaderText="<br/>Comment By" ItemStyle-Width="120px" HeaderStyle-Width="120px" ItemStyle-VerticalAlign="top"></telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="sprwc_CreationDate" UniqueName="sprwcc_CreationDate" HeaderText="<br/>CreationDate" ItemStyle-Width="75px" HeaderStyle-Width="75px" DataFormatString="{0:MM/dd/yyyy<br />HH:MM tt}" ItemStyle-VerticalAlign="Top"></telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="sprwc_Comment" UniqueName="sprwcc_Comment" HeaderText="<br/>Comment" ItemStyle-Width="10px"></telerik:GridBoundColumn>
                                        <telerik:GridTemplateColumn UniqueName="Attachments" HeaderText="<br>Attachments">
                                            <HeaderStyle HorizontalAlign="center" Width="70px" />
                                            <ItemStyle HorizontalAlign="center" VerticalAlign="top" Width="70px" />
                                            <ItemTemplate>
                                                <asp:LinkButton ID="lnkAttachments" runat="server" Text='<%# Eval("AttachmentCount")%>' CommandName="Edit"
                                                    Font-Size="8pt" CssClass="" ForeColor="Blue"></asp:LinkButton>
                                            </ItemTemplate>
                                        </telerik:GridTemplateColumn>
                                    </Columns>
                                    <CommandItemTemplate>
                                        <table>
                                            <tr>
                                                <td>
                                                    <asp:Button runat="server" ID="btnAddNewReply" Text=" " CommandName="InitInsert" CommandArgument="NewReply"
                                                        title="Reply" CssClass="rgAdd" />
                                                    <asp:LinkButton ID="lnkbAddReply" CssClass="Link" runat="server" CommandName="InitInsert" CommandArgument="NewReply">Reply</asp:LinkButton>
                                                </td>
                                                <td></td>
                                            </tr>
                                        </table>
                                    </CommandItemTemplate>

  27. Eyup
    Admin
    Eyup avatar
    3007 posts

    Posted 04 Feb Link to this post

    Hello,

    If you have difficulties accessing the Detail table views on client-side, you can check the script snippet provided in the following section to see an example:
    http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/hierarchical-grid-types-and-load-modes/traversing-detail-tables#looping-through-the-detail-tablesitems-in-telerik-radgrid-on-the-client

    Regards,
    Eyup
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017