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

RadButtonColumn not firing response or generating PDF

6 Answers 64 Views
Grid
This is a migrated thread and some comments may be shown as answers.
kieran
Top achievements
Rank 2
kieran asked on 16 Mar 2021, 11:12 AM

Hi all, I have a strange problem that I hope will have a simple solution.

I have a RadGrid in an asp.net webform.  This grid shows a list of reports that can be downloaded.

I have created a RadButtonColumn and set its CommandName to GetReport.

I am checking the ItemCommand event for this name and it is firing.

However the routine I am using to retrieve the PDF is not displaying the file for download.

 

If I put the same routine into a generic .net button, it fires without issue and acts as is expected.

 

See attached form structure and code behind.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FrmLotRegister.aspx.cs" Inherits="FrmLotRegister" Trace="false" EnableSessionState="False" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<head runat="server">
    <title></title>
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        </Scripts>
    </telerik:RadScriptManager>
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <div>
        <asp:SqlDataSource SelectCommand="SELECT DISTINCT Product, Binder, Date_Produced, Customer, Project, Location, Lot, Category, Job, Nata FROM View_Sample_Register WHERE (Nata > 0) AND (Product <> 'NULL')" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>" ProviderName="System.Data.SqlClient" ID="DataSource1" runat="server" ></asp:SqlDataSource>
        <telerik:RadGrid ID="RadGrid1" runat="server" ShowGroupPanel="True" DataSourceID="DataSource1"
        AllowSorting="True" AllowPaging="True" AllowFiltering="True" AllowFilteringByColumn="True" EnableLinqExpressions="False" OnItemCommand="RadGrid1_ItemCommand" OnPreRender="RadGrid1_PreRender" Skin="Black" AllowAutomaticUpdates="True">
            <MasterTableView GroupLoadMode="server" ShowGroupFooter="True" GroupsDefaultExpanded="False" AutoGenerateColumns="False">
                <Columns>
                    <telerik:GridBoundColumn DataField="Date_Produced" DataType="System.DateTime" FilterControlAltText="Filter Date_Produced column" HeaderText="Date_Produced" SortExpression="Date_Produced" UniqueName="Date_Produced">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Project" FilterControlAltText="Filter Project column" HeaderText="Project" SortExpression="Project" UniqueName="Project">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Job" FilterControlAltText="Filter Job column" HeaderText="Job" SortExpression="Job" UniqueName="Job">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Lot" FilterControlAltText="Filter Lot column" HeaderText="Lot" SortExpression="Lot" UniqueName="Lot">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Location" FilterControlAltText="Filter Location column" HeaderText="Location" SortExpression="Location" UniqueName="Location">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Product" FilterControlAltText="Filter Product column" HeaderText="Product" SortExpression="Product" UniqueName="Product">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Binder" FilterControlAltText="Filter Binder column" HeaderText="Binder" SortExpression="Binder" UniqueName="Binder">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Customer" FilterControlAltText="Filter Customer column" HeaderText="Customer" SortExpression="Customer" UniqueName="Customer">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Category" FilterControlAltText="Filter Category column" HeaderText="Category" SortExpression="Category" UniqueName="Category">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Nata" DataType="System.Int32" FilterControlAltText="Filter Nata column" HeaderText="Nata" SortExpression="Nata" UniqueName="Nata">
                    </telerik:GridBoundColumn>
                    <telerik:GridButtonColumn ButtonType="PushButton" CommandName="GetReport" DataTextField="Nata" FilterControlAltText="Filter column column" HeaderText="Report" UniqueName="column" CommandArgument="GetReport">
                    </telerik:GridButtonColumn>
                </Columns>
                <GroupByExpressions>
                    <telerik:GridGroupByExpression>
                        <SelectFields>
                            <telerik:GridGroupByField FieldAlias="Job" FieldName="Job" FormatString="" HeaderText="" />
                        </SelectFields>
                        <GroupByFields>
                            <telerik:GridGroupByField FieldAlias="Job" FieldName="Job" FormatString="" HeaderText="" />
                        </GroupByFields>
                    </telerik:GridGroupByExpression>
                    <telerik:GridGroupByExpression>
                        <SelectFields>
                            <telerik:GridGroupByField FieldAlias="Lot" FieldName="Lot" FormatString="" HeaderText="" />
                        </SelectFields>
                        <GroupByFields>
                            <telerik:GridGroupByField FieldAlias="Lot" FieldName="Lot" FormatString="" HeaderText="" />
                        </GroupByFields>
                    </telerik:GridGroupByExpression>
                </GroupByExpressions>
            </MasterTableView>
<GroupingSettings CollapseAllTooltip="Collapse all groups"></GroupingSettings>
 
            <ClientSettings AllowDragToGroup="True">
            </ClientSettings>
        </telerik:RadGrid>
    </div>
        <p>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        </p>
    </form>
</body>
</html>

 

and the code behind

 

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using LabassistEngineerPortal.Data;
using System.Linq;
 
public partial class FrmLotRegister : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    protected void RadGrid1_PreRender(object sender, EventArgs e)
    {
        //On first run sort only to show the last month
        if (!Page.IsPostBack)
        {
            RadGrid1.MasterTableView.FilterExpression = "([Date_Produced] > '" + DateTime.Today.AddMonths(-1).ToShortDateString() + "') ";
 
            GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("Date_Produced");
            column.CurrentFilterFunction = GridKnownFunction.GreaterThanOrEqualTo;
            column.CurrentFilterValue = DateTime.Today.AddMonths(-1).ToShortDateString();
            RadGrid1.GroupingEnabled = true;
            RadGrid1.MasterTableView.Rebind();
 
        }
 
 
    }
    //Take a Byte[] and turn it into a PDF for user download
    protected void Send_PDF(byte[] File, string Filename)
    {
        byte[] pdfdata = File;
        try
        {
            Response.Clear();
            Response.ContentType = "application/pdf";
 
            Response.BinaryWrite(pdfdata);
            string F = @"attachment;filename=""" + Filename + @"""";
            Response.AddHeader("content-disposition", F);
 
 
            Response.Cache.SetExpires(DateTime.Now.AddDays(7));
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetValidUntilExpires(true);
             
            Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    //The same routine is used in the RadButtonColumn control.
    //The routine fires but will not send the PDF at the end
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        //if button commandname is GetReport then fire this generic test function
        if (e.CommandName == "GetReport")
        {
            int? N = 4511;
            LabDatabase db = new LabDatabase();
            View_Sample_Register s = new View_Sample_Register();
            s = db.View_Sample_Register.FirstOrDefault(x => x.Nata == N);
            Nata_Reports r = new Nata_Reports();
            r = db.Nata_Reports.OrderByDescending(x => x.Revision).First(x => x.Nata_No.Value == N);
            string filename = s.Date_Produced.Value.Day + "-" + s.Date_Produced.Value.Month + "-" + s.Date_Produced.Value.Year + " " + s.Product + "-" + s.Binder + " " + s.Category + " " + r.Nata_No + ".pdf";
 
            Send_PDF(r.Report, filename);
 
        }
    }
 
    //when traditional .net button is used this routine works fine.
    protected void Button1_Click(object sender, EventArgs e)
    {
        int? N = 4511;
        LabDatabase db = new LabDatabase();
        View_Sample_Register s = new View_Sample_Register();
        s = db.View_Sample_Register.FirstOrDefault(x => x.Nata == N);
        Nata_Reports r = new Nata_Reports();
        r = db.Nata_Reports.OrderByDescending(x => x.Revision).First(x => x.Nata_No.Value == N);
        string filename = s.Date_Produced.Value.Day + "-" + s.Date_Produced.Value.Month + "-" + s.Date_Produced.Value.Year + " " + s.Product + "-" + s.Binder + " " + s.Category + " " + r.Nata_No + ".pdf";
 
        Send_PDF(r.Report, filename);
    }
}

 

What am I doing wrong here?  Why can I not seem to retrieve a file using the Gridviews buttonColumn?

 

6 Answers, 1 is accepted

Sort by
0
kieran
Top achievements
Rank 2
answered on 16 Mar 2021, 11:17 PM

To add to the original post, breakpoints indicate that Radgrid1_ItemCommand is being fired.  and it is identifying the command name GetReport.  it is firing Send_PDF  There is just no file download dialog at the end of it. 

The same routine works with the standard button and results in a file download dialog.

0
Doncho
Telerik team
answered on 19 Mar 2021, 07:26 AM

Hi Kieran,

Thank you for the provided information!

The issue you are facing is a result of the attempt to export the RadGrid via Ajax request. Since the RadGrid is Ajaxified by the RadAjaxManager the server-side code in the ItemCommand event is executed via Ajax request. Sending a response to the browser is only possible with a postback. You can find more about this scenario in the Export from Ajaxified Grid article.

In the current case, you can use the client-side OnCommand event of the RadGrid to disable Ajax when the specific command is fired. You will need to get a reference to the RadAjaxManager (see Get Client-side Reference to a Control Object) and use its set_enableAJAX() method (RadAjaxManager Object)

Here is a sample JavaScript code you can try:

<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
    <script>
        function OnCommand(sender, args) {
            if (args.get_commandName() == "GetReport") {
                var ajaxManager = $find('<%= RadAjaxManager1.ClientID %>');
                ajaxManager.set_enableAJAX(false);
            }
        }
    </script>
</telerik:RadScriptBlock>

Please give it a try and let me know how it goes.

Kind regards,
Doncho
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

0
kieran
Top achievements
Rank 2
answered on 21 Mar 2021, 11:53 PM

Thanks Doncho, disabling Ajax did the trick.

Thanks again mate.

0
kieran
Top achievements
Rank 2
answered on 22 Mar 2021, 04:51 AM

Hi Mate,

              This allows the routine to fire, but it seems that it posts back before the event has occured.  the routine is losing the currently selected record and returning the first record in the bound list.  Is there any way around this?

0
Accepted
Doncho
Telerik team
answered on 23 Mar 2021, 02:33 PM

Hi Kieran,

I have posted an answer to your question in the formal support ticket you have opened on the topic.

I will post my answer here as well so others can also see it:

When the RadGrid is Ajaxified you can use the [GridCommanEventArgs].CommandArgument as it will point to the item index by default (unless the CommandArgument in the GridButtonColumn is explicitly set).

By using the index you can reach the clicked item in the [RadGrid].Items collection and get its DataKeyValue:

protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName=="GetReport")
    {
        var clickedItemIndex = int.Parse(e.CommandArgument.ToString());
        var dataKeyValue = RadGrid1.Items[clickedItemIndex].GetDataKeyValue("Nata");
    }
}

Alternatively, you can use GridTemplateColumn instead and pass the desired value as a CommandArgument as suggested in the following forum answer - https://www.telerik.com/forums/gridbuttoncolumn-commandargument-parameter#YG-Nv0JdP02UeghVw8TJ7g

In case further questions come up, I would suggest you proceed with the communication in the support thread only.

Kind regards,
Doncho
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

0
kieran
Top achievements
Rank 2
answered on 24 Mar 2021, 12:03 PM
Thanks Doncho, I will likely take that rout, and from now on only post in the forum if it brings something to the troubleshooting pool.  Thanks again for your help.
Tags
Grid
Asked by
kieran
Top achievements
Rank 2
Answers by
kieran
Top achievements
Rank 2
Doncho
Telerik team
Share this question
or