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

Calling the ItemCommand Handler from JavaScript

25 Answers 1234 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Reid
Top achievements
Rank 2
Reid asked on 29 Jan 2009, 04:38 AM
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

25 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 29 Jan 2009, 05:54 AM
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.
0
Reid
Top achievements
Rank 2
answered on 29 Jan 2009, 02:36 PM
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?
0
Reid
Top achievements
Rank 2
answered on 29 Jan 2009, 02:59 PM
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.
0
Daniel
Telerik team
answered on 30 Jan 2009, 01:53 PM
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.
0
Reid
Top achievements
Rank 2
answered on 30 Jan 2009, 02:09 PM
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.
0
Yavor
Telerik team
answered on 30 Jan 2009, 02:34 PM
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.
0
Reid
Top achievements
Rank 2
answered on 31 Jan 2009, 04:51 PM
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.
0
Reid
Top achievements
Rank 2
answered on 31 Jan 2009, 05:46 PM
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;  
                        }  
         }  
       }  
   }  

0
Reid
Top achievements
Rank 2
answered on 01 Feb 2009, 11:11 PM
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.
0
Yavor
Telerik team
answered on 02 Feb 2009, 10:57 AM
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.
0
Reid
Top achievements
Rank 2
answered on 02 Feb 2009, 02:12 PM
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

0
Yavor
Telerik team
answered on 02 Feb 2009, 02:49 PM
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.
0
Reid
Top achievements
Rank 2
answered on 02 Feb 2009, 03:49 PM
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? 
0
Yavor
Telerik team
answered on 05 Feb 2009, 11:40 AM
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.
0
Reid
Top achievements
Rank 2
answered on 05 Feb 2009, 03:21 PM
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
0
Reid
Top achievements
Rank 2
answered on 07 Feb 2009, 02:27 PM
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
0
Amarendra Parab
Top achievements
Rank 1
answered on 16 Feb 2010, 02:56 PM
// 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".
0
Amarendra Parab
Top achievements
Rank 1
answered on 17 Feb 2010, 10:06 AM
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
0
Iana Tsolova
Telerik team
answered on 18 Feb 2010, 01:21 PM
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.
0
Amarendra Parab
Top achievements
Rank 1
answered on 18 Feb 2010, 02:08 PM

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

0
Iana Tsolova
Telerik team
answered on 18 Feb 2010, 03:05 PM
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.
0
RBarnes
Top achievements
Rank 1
answered on 27 Jan 2016, 03:14 PM

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?

0
Eyup
Telerik team
answered on 01 Feb 2016, 12:20 PM
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
0
RBarnes
Top achievements
Rank 1
answered on 01 Feb 2016, 03:54 PM

 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>

0
Eyup
Telerik team
answered on 04 Feb 2016, 11:34 AM
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
Tags
Grid
Asked by
Reid
Top achievements
Rank 2
Answers by
Princy
Top achievements
Rank 2
Reid
Top achievements
Rank 2
Daniel
Telerik team
Yavor
Telerik team
Amarendra Parab
Top achievements
Rank 1
Iana Tsolova
Telerik team
RBarnes
Top achievements
Rank 1
Eyup
Telerik team
Share this question
or