Model Popup showing as blank when click view button in gridview C#

BeUnique 2,212 Reputation points
2024-11-11T13:27:24.9366667+00:00

I am using ASP.NET application and i used Gridview to show the PDF file.

when i click the view button in the gridview, the file will be opening is perfect.

I am using some search button outside the gridview for filter records in gridview.

Whenever i am using search filter, the gridview has filtered, but, when i click the view button, popup will be displaying as blank at very first time or the previous file will be displaying.

What could be the problem and how to solve this.

below is my code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test_Pagination.aspx.cs" Inherits="Test_Pagination" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test - Grid Freeze</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/4.1.0/js/dataTables.fixedColumns.min.js"></script>
    <link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.datatables.net/fixedcolumns/4.1.0/css/fixedColumns.dataTables.min.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .auto-style1 {
            width: 600px;
            border-style: solid;
            border-width: 2px;
        }
        .dataTables_scrollHead {
            width: 600px !important;
        }
        .dataTables_scrollHeadInner {
            width: 600px !important;
        }
        .dataTables_scrollBody {
            width: 600px !important;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $('#gvCustomer tfoot tr').appendTo('#gvCustomer thead');
            $('#gvCustomer').removeAttr('width').DataTable({
                bFilter: true,
                bSort: true,
                scrollY: "150px",
                scrollCollapse: true,
                paging: false,
                fixedColumns: false,
                orderCellsTop: true
            });
        });
    </script>
     <%-- //********* Script for myModel - Modal Popup  ******************//--%>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
 <%--<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>--%>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 <script type='text/javascript'>
     function openModal() {
         $('[id*=PopModal]').modal('show');
     }
 </script>
 <%--  //********* Script for myModel  - Modal Popup  ******************//--%>
     <%-- //***** for search dropdown stylesheet and js files *************--%>
 <%--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />--%>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
 <%--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>--%>
 <%--<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>--%>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>
 <script type="text/javascript">
     $(function () {
         $("[id*=drpEmployee]").selectpicker();
     });
     //On UpdatePanel Refresh
     var prm = Sys.WebForms.PageRequestManager.getInstance();
     if (prm != null) {
         prm.add_endRequest(function (sender, e) {
             if (sender._postBackSettings.panelsToUpdate != null) {
                 $("[id*=drpEmployee]").selectpicker();
             }
         });
     };
 </script>
  <script type="text/javascript">
        window.onload = function () {
            var grid = document.getElementById('<%= gvCustomer.ClientID %>');
            var tbody = grid.getElementsByTagName("tbody")[0]; //gets the first and only tbody
            var firstTr = tbody.getElementsByTagName("tr")[0]; //gets the first tr, hopefully contains the th's
            tbody.removeChild(firstTr); //remove tr's from table
            var newTh = document.createElement('thead'); //creates thead
            newTh.appendChild(firstTr); //puts ths in thead
            grid.insertBefore(newTh, tbody); //puts thead behore tbody
        }
    </script>
    <script type="text/javascript">
        function SelectAll(headerCheckBox) {
            //Get the reference of GridView.
            var GridView = document.getElementById("gvCustomer");
            //Loop through all GridView Rows except first row.
            for (var i = 1; i < GridView.rows.length; i++) {
                //Reference the CheckBox.
                var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
                checkBox.checked = headerCheckBox.checked;
            }
        }
    </script>
    <script type="text/javascript">
        function SelectOne(chk) {
            //Get the reference of GridView.
            var GridView = chk.parentNode.parentNode.parentNode.parentNode;
            //Reference the Header CheckBox.
            var headerCheckBox = GridView.rows[0].cells[0].getElementsByTagName("input")[0];;
            var checked = true;
            //Loop through all GridView Rows.
            for (var i = 1; i < GridView.rows.length; i++) {
                //Reference the CheckBox.
                var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
                if (!checkBox.checked) {
                    checked = false;
                    break;
                }
            }
            headerCheckBox.checked = checked;
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div class="modal fade" id="PopModal" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">
                            &times;</button>
                        <h4 class="modal-title">Invoice Details</h4>
                    </div>
                    <div class="modal-body">
                        <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
                            <div class="form-group">
                                <asp:Label ID="Label1" runat="server" CssClass="tdLabel" Text="File Name :"></asp:Label>
                                <asp:Label ID="lblFileName" CssClass="tdLabel" runat="server" Text="Label"></asp:Label>
                            </div>
                            <div class="form-group">
                                <asp:Label ID="lblid" runat="server" Text=""></asp:Label>
                            </div>
                            <div class="form-group">
                                <iframe id="iframe" runat="server" width="500" height="500"></iframe>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <asp:ScriptManager ID="ScrMgr2" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server" ID="UpdatePanel1">
            <ContentTemplate>
                <table style="font-family: 'Blender Pro'; font-weight: bold; font-size: 16px; width: 100%; color: #22505F;">
                    <tr>
                        <td>
                            <asp:Label ID="lblDispName" runat="server" Text="Employee Name :"></asp:Label>
                            <asp:DropDownList ID="drpEmployee" runat="server"
                                AutoPostBack="true" class="selectpicker" data-live-search="true">
                            </asp:DropDownList>
                        </td>
                        <td align="left" style="width: 40%">
                            <asp:Button ID="btnSearch" runat="server" CssClass="btnGenerate" Text="SEARCH" OnClick="btnSearch_Click" />
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            <asp:Button ID="btnClear" runat="server" CssClass="btnGenerate" Text="CLEAR" OnClick="btnClear_Click" />
                        </td>
                    </tr>
                </table>
            </ContentTemplate>
        </asp:UpdatePanel>
        <div id="dvGrid" style="width: 100%">
            <asp:UpdatePanel runat="server" ID="UpdatePanel2">
                <ContentTemplate>
                    <asp:GridView ID="gvCustomer" Width="100%" AutoGenerateColumns="False" runat="server"
                        Font-Size="12px"
                        DataKeyNames="Id">
                        <AlternatingRowStyle BackColor="white" />
                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkAll" runat="server" onclick="SelectAll(this)" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chk" runat="server" onclick="SelectOne(this)" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="ID">
                                <ItemTemplate>
                                    <asp:Label ID="Id" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">Sl No.</label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <%# Container.DataItemIndex + 1 %>
                                </ItemTemplate>
                                <ItemStyle HorizontalAlign="Center" />
                            </asp:TemplateField>
                            <asp:TemplateField ItemStyle-HorizontalAlign="left">
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">Emp No.</label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblCustNo" Style="text-align: left; line-height: 28px;"
                                        runat="server" Text='<%# Eval("EmpId")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                              <asp:TemplateField ItemStyle-HorizontalAlign="left">
                        <HeaderTemplate>
                            <label style="text-align: center; display: block;">Emp Name.</label>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblCustName" Style="line-height: 28px;"
                                runat="server" Text='<%# Eval("EmpName")%>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                            <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                                <HeaderTemplate>
                                    <label style="text-align: center; display: block;">
                                        View File
                                    </label>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkBtnView" runat="server" Text="View"
                                        OnClick="Display"></asp:LinkButton>
                                    <asp:HiddenField ID="HiddenField1" runat="server"
                                        Value='<%# Eval("FilePath")%>' />
                                    <asp:HiddenField ID="HdnFileName" runat="server"
                                        Value='<%# Eval("FileName")%>' />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <HeaderStyle BackColor="#2F6370" Font-Names="Arial" Font-Size="12px" ForeColor="White" />
                        <SelectedRowStyle BackColor="#007D8C" Font-Bold="True" ForeColor="White" />
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

ASPX.CS
********
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.IO;
namespace Test
{
    public partial class Test_Pagination : System.Web.UI.Page
    {
        private string str = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        string sRoot = @"\\net.venem.intranet\srv1\Team10\IT\AccFiles\";
        DataTable rstData = new DataTable();
        private DataSet ds = new DataSet();
        public string EmpNo = string.Empty;
        public string EmpName = string.Empty;
      
        private string filename = string.Empty;
        private string FileType = String.Empty;
        //private DateTime dtBillDate;
     
        protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                try
                {
                    //****** To get emp name and assign to label
                    //lblFileUploadName.Text = "";
                    if (HttpContext.Current.Session["Empno"] == null)
                    {
                        Response.Redirect("SessionExpired.aspx");
                    }
                    else
                    {
                        EmpName = HttpContext.Current.Session["EmpName"].ToString();
                        EmpNo = HttpContext.Current.Session["Empno"].ToString();
                        //lblEmpName.Text = string.Concat(EmpName, StrHyphen, EmpNo);
                    }
                    GetEmpDetails();
                    GetEmpAccDetails();
                    Session["rstData"] = rstData;
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    // ds = Nothing
                    // ds.Dispose()
                }
            }
            else
            {
                rstData = Session["rstData"] as DataTable;
            }
            foreach (var item in gvCustomer.Rows)
            {
                LinkButton btnDisplay = (LinkButton)((GridViewRow)item).FindControl("lnkBtnView");
                // Get current ScriptManager on the page
                ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnDisplay);
                if (!string.IsNullOrEmpty(btnDisplay.CommandArgument))
                {
                    ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnDisplay);
                }
            }
        }
        private void GetEmpDetails()
        {
            try
            {
                dbConn.sqlCmd.Parameters.Clear();
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_TYPE", "GET_EmpList");
                ds = dbConn.XcuteResult(str, CommandType.StoredProcedure, "Spd_EmpDetails_Master");
                drpEmployee.DataSource = ds.Tables[0].DefaultView;
                drpEmployee.DataTextField = ds.Tables[0].Columns[0].ColumnName;
                drpEmployee.DataValueField = ds.Tables[0].Columns[0].ColumnName;
                drpEmployee.DataBind();
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                ds = null;
            }
        }
        private void GetEmpAccDetails()
        {
            try
            {
                dbConn.sqlCmd.Parameters.Clear();
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_Type", "GetEmpAccDetails");
                //dbConn.sqlCmd.Parameters.AddWithValue("@Spd_Flag", Flag.ToString().Trim());
                ds = dbConn.XcuteResult(str, CommandType.StoredProcedure, "Spd_EmpDetails_Master");
                if ((ds.Tables[0].Rows.Count > 0))
                {
                    //gvBills.Visible = true;
                    rstData = ds.Tables[0];
                    gvCustomer.DataSource = rstData;
                    gvCustomer.DataBind();
                    //lblNoRecord.Visible = false;
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
               
            }
            finally
            {
                ds = null;
            }
           
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string ddlEmpvalue = string.Empty;
            if (drpEmployee.SelectedValue == "")
            {
                ddlEmpvalue = "";
            }
            else
            {
                ddlEmpvalue = drpEmployee.SelectedValue;
            }
          
            try
            {
                dbConn.sqlCmd.Parameters.Clear();
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_TYPE", "Search_EmpDetails");
                dbConn.sqlCmd.Parameters.AddWithValue("@Spd_EmpNo", ddlEmpvalue.ToString().Trim()); //Employee value
                ds = dbConn.XcuteResult(str, CommandType.StoredProcedure, "Spd_EmpDetails_Master");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    gvCustomer.DataSource = ds.Tables[0];
                    gvCustomer.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    gvCustomer.DataSource = ds.Tables[0];
                    gvCustomer.DataBind();
                    int TotalColumns = gvCustomer.Rows[0].Cells.Count;
                    gvCustomer.Rows[0].Cells.Clear();
                    //gvCustomer.Rows[0].Cells.Add(new TableCell());
                    gvCustomer.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                    gvCustomer.Rows[0].Cells[0].Text = "No record(s) Found";
                }
               
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                ds = null;
            }
        }
        protected void btnClear_Click(object sender, EventArgs e)
        {
            drpEmployee.SelectedIndex = -1;
            GetEmpAccDetails();
        }
        protected void Display(object sender, EventArgs e)
        {
            Session["FPath"] = null;
            int rowIndex = Convert.ToInt32(((sender as LinkButton).NamingContainer as GridViewRow).RowIndex);
            GridViewRow row = gvCustomer.Rows[rowIndex];
            string FPath = (row.FindControl("HiddenField1") as HiddenField).Value;
            Session["FPath"] = FPath;
            HiddenField HiddenField1 = (row.FindControl("HiddenField1") as HiddenField);
            string FileName = (row.FindControl("HdnFileName") as HiddenField).Value;
            string sMineType = MimeMapping.GetMimeMapping(FPath);
            if (!string.IsNullOrEmpty(FPath))
            {
                if (File.Exists(FPath))
                {
                    lblFileName.Text = FileName.ToString();
                    byte[] rawFile = File.ReadAllBytes(FPath);
                    iframe.Attributes["src"] = $@"data:{sMineType};base64,{Convert.ToBase64String(rawFile)}";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "No Data", "alert(\'File is missing in the folder..!.\');", true);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "No Data", "alert(\'No data found..!.\');", true);
            }
            HiddenField1.Visible = false; //Hide the path
        }
    }
}



ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,522 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,064 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 29,911 Reputation points Microsoft Vendor
    2024-11-13T07:15:40.9433333+00:00

    Hi @BeUnique,

    Put the popup content inside the update panel.

    <asp:ScriptManager ID="ScrMgr2" runat="server"></asp:ScriptManager>
     <asp:UpdatePanel runat="server" ID="UpdatePanel3">
         <ContentTemplate>
             <div class="modal fade" id="PopModal" role="dialog">
                 <div class="modal-dialog">
                     <!-- Modal content-->
                     <div class="modal-content">
                         <div class="modal-header">
                             <button type="button" class="close" data-dismiss="modal">
                                 &times;</button>
                             <h4 class="modal-title">Invoice Details</h4>
                         </div>
                         <div class="modal-body">
                             <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
                                 <div class="form-group">
                                     <asp:Label ID="Label1" runat="server" CssClass="tdLabel" Text="File Name :"></asp:Label>
                                     <asp:Label ID="lblFileName" CssClass="tdLabel" runat="server" Text="Label"></asp:Label>
                                 </div>
                                 <div class="form-group">
                                     <asp:Label ID="lblid" runat="server" Text=""></asp:Label>
                                 </div>
                                 <div class="form-group">
                                     <iframe id="iframe" runat="server" width="500" height="500"></iframe>
                                 </div>
                             </div>
                         </div>
                     </div>
                 </div>
             </div>
         </ContentTemplate>
     </asp:UpdatePanel>
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread


5 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,406 Reputation points
    2024-11-12T17:04:09.9+00:00

    the modal popup is not in the update panel, so iframe source is not updated by the update panel code.

    also I question passing the pdf as a base64 url in an ajax response, unless they are really small. you should pass a link.

    0 comments No comments

  2. SurferOnWww 3,286 Reputation points
    2024-11-13T06:19:10.45+00:00

    i click the view button, popup will be displaying as blank at very first time or the previous file will be displaying.

    I guess that it is because you placed the iframe out of UpdatePanel as @Bruce (SqlWork.com) mentioned in his answer.

    Rather than using Display method to set the base64 data to the src attribute of iframe on post back I suggest you use JavaScript to set the file path to the src of iframe at client side without post back.

    Please consider placing the pdf files under project root or virtual directory of the application as shown below:

    enter image description here

    Then, set JavaScript method to OnClientClick property of LinkButton to set the path of pdf file to the scr attributre of iframe.

    Sample code is shown below:

    .aspx.cs

    using System;
    using System.Data;
    
    namespace WebForms1
    {
        public partial class WebForm50 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    GridView1.DataSource = CreateDataTable();
                    GridView1.DataBind();
                }
            }
    
            protected string SetOnClientClick(string filePath)
            {
                return $"SetPathToSrc('{filePath}'); return false;";
            }
    
            protected DataTable CreateDataTable()
            {
                var table = new DataTable();
                table.Columns.AddRange(new DataColumn[5] 
                {
                    new DataColumn("Id", typeof(int)),
                    new DataColumn("EmpId", typeof(string)),
                    new DataColumn("EmpName", typeof(string)),
                    new DataColumn("FileName",typeof(string)),
                    new DataColumn("FilePath",typeof(string))
                });
                table.Rows.Add(1, "E101", "AAA", "Invoice1.pdf", "/Files/ASP.NETCore.pdf");
                table.Rows.Add(2, "E102", "BBB", "Invoice2.pdf", "/Files/important_car.pdf");
                table.Rows.Add(3, "E103", "CCC", "Invoice3.pdf", "/Files/JBL4312G.pdf");
                table.Rows.Add(4, "E104", "DDD", "Invoice4.pdf", "/Files/motorcompetition.pdf");
                table.Rows.Add(5, "E105", "EEE", "Invoice5.pdf", "/Files/test.pdf");
    
                return table;
            }
        }
    }
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true"
        CodeBehind="WebForm50.aspx.cs"
        Inherits="WebForms1.WebForm50" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript">
            function SetPathToSrc(filePath) {
                const iframe = document.getElementById("iframe");
                iframe.src = filePath;
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="Id" HeaderText="Id" />
                    <asp:BoundField DataField="EmpId" HeaderText="EmpId" />
                    <asp:BoundField DataField="EmpName" HeaderText="EmpName" />
                    <asp:BoundField DataField="FileName" HeaderText="FileName" />
                    <asp:TemplateField HeaderText="View File">
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" 
                                runat="server" 
                                Text="View"
                                OnClientClick='<%# SetOnClientClick((string)Eval("FilePath")) %>'/>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    
            <iframe id="iframe" width="500" height="500"></iframe>
        </form>
    </body>
    </html>
    

    clicking [View] shows pdf in iframe:

    enter image description here

    Please let me know if you cannot place the pdf files other than file server currently used. I will be able to suggest alternative plan which uses a HTTP handler.


  3. SurferOnWww 3,286 Reputation points
    2024-11-13T06:19:57.8766667+00:00

    This answer has been deleted because of duplication.


  4. SurferOnWww 3,286 Reputation points
    2024-11-14T03:31:59.85+00:00

    As per our policy, documents (Pdf,Word,excel,etc) should not be stored in application folder. All the documents should keep maintained in File Server or Sharepoint folder only.

    In this case, how to proceed....?

    I understand the account of worker process has proper access right to the pdf files in File Server and that's why you could obtain the byte array using byte[] rawFile = File.ReadAllBytes(FPath); in the Display method in your .aspx.cs.

    Try using a HTTP generic handler and set it to the scr attribute of iframe.

    The HTTP generic handler shall receive value from query string which is corresponding to the value of Id field in the Test_EmpDetails table of SQL Server, obtain the value of FilePath field in the Test_EmpDetails table using id passed by query string, obtain byte array of pdf file and write the byte array to the response stream.

    You mentioned:

    Also, we are using base64,{Convert.ToBase64String(rawFile) for avoiding to see the file path in client browser.

    User will never be able to see the file path if you use the HTTP handler properly. As I mentioned in my comment, be aware that you set the file path in the hidden field and user can see it as he can display the source code of html on his browser.

    In addition and most importantly you can avoid writing the complicated code which uses Display method to set the base64 data to the src attribute of iframe on post back and includes the iframe in UpdatePanel.

    Below is sample code of the HTTP generic handler:

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web;
    using System.Web.Configuration;
    
    namespace WebForms1
    {
        /// <summary>
        /// Summary description for Handler5
        /// </summary>
        public class Handler5 : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                // Obtain value sent via query string;
                string value = context.Request.QueryString["id"];
    
                // Obatin file path from SQL Server using id passed by query string
                int id;
                string filePath;
                if (value != null && int.TryParse(value, out id))
                {
                    var query = "SELECT [FilePath] FROM [Test_EmpDetails] WHERE [id] = @id";
                    string connString = WebConfigurationManager
                                        .ConnectionStrings["TestDatabaseConnectionString"]
                                        .ConnectionString;
    
                    using (var connection = new SqlConnection(connString))
                    {
                        using (var command = new SqlCommand(query, connection))
                        {
                            var param = new SqlParameter("@id", SqlDbType.Int);
                            command.Parameters.Add(param);
                            command.Parameters["@id"].Value = id;
                            connection.Open();
                            filePath = (string)command.ExecuteScalar();
                        }
                    }
    
                    // set cache controls as required
                    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    context.Response.Cache.SetExpires(DateTime.Now.ToUniversalTime());
                    context.Response.Cache.SetMaxAge(new TimeSpan(0, 0, 0, 0));
    
                    context.Response.ContentType = "application/pdf";
    
                    // Obtain byte array of pdf file specified by filePath above.
                    // Account of worker process must have access right to the file
                    byte[] data = System.IO.File.ReadAllBytes(filePath);
    
                    // Write byte array to response stream
                    context.Response.BinaryWrite(data);
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

    Rewrite the .aspx.cs and .aspx to use the above Handler5.ashx as shown below:

    .aspx.cs

    using System;
    
    // 2024/11/13 Microsoft Q&A の検証用
    // https://learn.microsoft.com/en-us/answers/questions/2117788/model-popup-showing-as-blank-when-click-view-butto
    
    namespace WebForms1
    {
        public partial class WebForm50 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {            
            }
    
            protected string SetOnClientClick(int id)
            {
                return $"SetPathToSrc({id}); return false;";
            }
        }
    }
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true"
        CodeBehind="WebForm50.aspx.cs"
        Inherits="WebForms1.WebForm50" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript">
            function SetPathToSrc(id) {
                const iframe = document.getElementById("iframe");
                iframe.src = "Handler5.ashx?id=" + id;
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:SqlDataSource ID="SqlDataSource1" 
                runat="server" 
                ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>" 
                SelectCommand="SELECT [Id], [EmpId], [EmpName], [FileName] FROM [Test_EmpDetails]">
            </asp:SqlDataSource>
            <asp:GridView ID="GridView1" 
                runat="server" 
                AutoGenerateColumns="False" 
                DataKeyNames="Id" 
                DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="Id" 
                        HeaderText="Id" 
                        InsertVisible="False" ReadOnly="True" SortExpression="Id" />
                    <asp:BoundField DataField="EmpId" 
                        HeaderText="EmpId" SortExpression="EmpId" />
                    <asp:BoundField DataField="EmpName" 
                        HeaderText="EmpName" SortExpression="EmpName" />
                    <asp:BoundField DataField="FileName" 
                        HeaderText="FileName" SortExpression="FileName" />
                    <asp:TemplateField HeaderText="View File">
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" 
                                runat="server" 
                                Text="View"
                                OnClientClick='<%# SetOnClientClick((int)Eval("Id")) %>'/>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    
            <iframe id="iframe" width="500" height="500"></iframe>
        </form>
    </body>
    </html>
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.