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

Problem with Button in CommandItemTemplate

10 Answers 689 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Doug Rutledge
Top achievements
Rank 1
Doug Rutledge asked on 22 Jul 2008, 04:36 PM
I have a RadGrid on my page, with a button in the CommandItemTemplate.  I want to execute a client function to determine if I need to postback to do some work to do something else on the client side.  When I do this, the button no longer causes a postback.  It will not postback even if I simplet do OnClientClick="return true;".  Is there a way to work around this.  Here is some sample code.

ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridTest._Default" %> 
 
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server">  
    <title>Untitled Page</title> 
    <script language="javascript" type="text/javascript">  
        function onBtnClick()  
        {  
            return true;  
        }  
    </script> 
</head> 
<body> 
    <form id="form1" runat="server">  
    <telerik:RadScriptManager runat="server">  
    </telerik:RadScriptManager> 
       <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">  
        <AjaxSettings> 
            <telerik:AjaxSetting AjaxControlID="RadGrid1">  
                <UpdatedControls> 
                    <telerik:AjaxUpdatedControl ControlID="lbl" /> 
                </UpdatedControls> 
            </telerik:AjaxSetting> 
        </AjaxSettings> 
    </telerik:RadAjaxManager> 
    <div> 
    <asp:Label ID="lbl" runat="server"></asp:Label> 
        <telerik:RadGrid ID="RadGrid1" Skin="WebBlue" Width="500" runat="server" GridLines="None"   
            onitemcommand="RadGrid1_ItemCommand">  
          
<MasterTableView CommandItemDisplay="Top">  
    <CommandItemTemplate> 
        <asp:Button ID="btnCmd" CommandName="ShowTime" OnClientClick="return onBtnClick();" runat="server" Text="Do Something" /> 
    </CommandItemTemplate> 
<RowIndicatorColumn> 
<HeaderStyle Width="20px"></HeaderStyle> 
</RowIndicatorColumn> 
 
<ExpandCollapseColumn> 
<HeaderStyle Width="20px"></HeaderStyle> 
</ExpandCollapseColumn> 
</MasterTableView> 
          
        </telerik:RadGrid> 
      
    </div> 
   
    </form> 
</body> 
</html> 

Here is the c# code behind:
using System;  
using System.Collections;  
using System.Collections.Generic;  
using System.Configuration;  
using System.Data;  
using System.Linq;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.HtmlControls;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Xml.Linq;  
 
namespace GridTest  
{  
    public partial class _Default : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!IsPostBack)  
            {  
                List<Sample> sampleList = new List<Sample>();  
                for (int x = 0; x < 15; x++)  
                {  
                    Sample s = new Sample();  
                    s.Name = String.Format("Name {0}", x);  
                    s.Description = String.Format("Description for item {0}", x);  
                    sampleList.Add(s);  
                }  
 
                RadGrid1.DataSource = sampleList;  
                RadGrid1.DataBind();  
            }  
        }  
 
        protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)  
        {  
            if (e.CommandName == "ShowTime")  
            {  
                lbl.Text = String.Format("Processed at {0}.", DateTime.Now.ToLongTimeString());  
            }  
        }  
    }  
 
    public class Sample  
    {  
        public string Name { get; set; }  
        public string Description { get; set; }  
    }  
}  
 

Thanks,
Doug

10 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 23 Jul 2008, 10:09 AM
Hi Doug,

Can you try moving the JavaScript code from the Head tag to the Body tag and see whether it is working.

ASPX:
  <CommandItemTemplate> 
        <asp:Button ID="Button2" runat="server" CommandName="ShowTime"  Text="Button" OnClientClick="return Click();" OnClick="Button2_Click" /> 
     </CommandItemTemplate> 

JS:
<body> 
        
        <script type="text/javascript"   language="javascript" > 
         
         function Click() 
          { 
          alert('Return') 
           return true;   
          } 
          
        </script> 
 
       .... 
</body> 


Thanks
Shinu.
0
Doug Rutledge
Top achievements
Rank 1
answered on 23 Jul 2008, 01:57 PM
Moving the javascript didn't fix my problem.  It still doesn't postback to the server when the button is clicked.  I even tried OnClientClick="return true;" and that didn't work.
0
Doug Rutledge
Top achievements
Rank 1
answered on 23 Jul 2008, 02:20 PM
I found a work around.  Please let me know if someone knows of a better way to address this.  My new javascript looks like this:

<script language="javascript" type="text/javascript">  
        function onBtnClick(ctl)  
        {  
            __doPostBack(ctl, "");  
            return true;  
        }  
</script> 

I pass the unique id of the button in the command template to the javascript function and manually fire the postback.  I assign the OnClientClick value for the button programmatically after the RadGrid is bound.

RadGrid1.DataBind();  
 
foreach (GridItem item in RadGrid1.MasterTableView.GetItems(GridItemType.CommandItem))  
                {  
                    Button btn = item.FindControl("btnCmd"as Button;  
                    btn.OnClientClick = String.Format("return onBtnClick(\"{0}\");", btn.UniqueID);  
                } 

This seems to work in my sample/sandbox project, so I'm going to try and use it in my real project.

Doug
0
Felipe Saldana
Top achievements
Rank 1
answered on 02 Apr 2009, 10:22 PM
I am running into the same problem....is there a proper solution for this yet.

I too am looking for a more proper way to address this situation.
0
Sebastian
Telerik team
answered on 03 Apr 2009, 06:36 AM

Hello guys,

More convenient approach for you might be to intercept the OnCommand client event of the grid, determine the command which has been fired based on the CommandName value of the button through the eventArgs.get_commandName() argument in the OnCommand handler and execute your custom logic based on that.

After this event the grid will still postback and raise its ItemCommand server event unless you explicitly cancel the postback by setting eventArgs.set_cancel(true) in the OnCommand event handler.

Best regards,

Sebastian
the Telerik team

Check out Telerik Trainer , the state of the art learning tool for Telerik products.
0
Felipe Saldana
Top achievements
Rank 1
answered on 05 Apr 2009, 04:19 PM

My case has a RadToolbar in the CommandItemTemplate and the Grid Command event would not fire when a button from the toolbar was clicked.

But I followed what you said and did the exact same thing for the OnClientButtonClicking event on the RadToolbar and it worked great.


Thanks!

 

 

 

0
Anthony
Top achievements
Rank 1
answered on 08 May 2009, 02:29 AM
Turns out that the reason for this is that the __postBack call is placed in a string of Javascript commands after the onClientClick code:

onClick='your javascript commands; __postBack'

So, if you have ANY "Return", either true or false, this stops execution before it gets to the postback.

SO, what you WANT to do is only do a return if you DON'T want a postback.

So, something like:

if (nopostpack condition) return false;

Hence:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // only want to work with DataRows
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // determine the numComments & numRatings amounts
            decimal numComments = Int32.Parse(DataBinder.Eval(e.Row.DataItem, "NumComments").ToString());
            decimal numRatings = Int32.Parse(DataBinder.Eval(e.Row.DataItem, "NumRatings").ToString());

            //Get a reference to Delete button.  Since there is an Edit and a spacer, it's index 2.
            Button b = (Button)e.Row.Cells[0].Controls[2];

            //Set the onClientClick to ask for confirmation before deleting any albums with child records
            b.OnClientClick = String.Format("if (!AllowDelete({0},{1})) return false;", numComments, numRatings);
        }
    }
0
kachy
Top achievements
Rank 1
answered on 23 Mar 2010, 04:56 PM

I am having the exact same problem. OnCLientClick of a button in CommandItemTemplate does not do that postback. Please help.
if I do

OnClientClick="javascript:return confirm('Status will change, are you sure?')"

, it gives the confirmation message but does not do postback.
If I just do

OnClientClick="javascript:confirm('Status will change, are you sure?')",
it gives the confirmation message but does not stop the postback on cancel also.

I also tried OnCommand but read somewhere that onCommand client event works only for the default commands not the custom command. Please help. I have to do the confirmation and also some other check before the postback on ClientClick of a custom command.

0
Anthony
Top achievements
Rank 1
answered on 24 Mar 2010, 02:25 AM
How about:

OnClientClick="javascript:if (!confirm('Status will change, are you sure?')") return false;"

That way, if (as happened with me) it appends the postback javascript to the end of what  you define, then if the confirm returned false, you return false, and thus interrupt the sequence before the postback can happen, but if the confirm returns true, you do nothing, and the postback happens as normal.  Or at least, that's the way I read it.

Good luck!

0
kachy
Top achievements
Rank 1
answered on 24 Mar 2010, 02:00 PM
It worked. Thanks
Tags
Grid
Asked by
Doug Rutledge
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Doug Rutledge
Top achievements
Rank 1
Felipe Saldana
Top achievements
Rank 1
Sebastian
Telerik team
Anthony
Top achievements
Rank 1
kachy
Top achievements
Rank 1
Share this question
or