[Solved] Button Click not firing inside ASP.Net UpdatePanel with Master Page

Last Reply 23 days ago By pandeyism

Posted 24 days ago

What I am doing is loading a text file and then viewing it in a grid view, but I made a menu using html and CSS that is loaded from the database, the problem is that when I click on the button to view the file in the gridview, the menu on the left side disappears, so I tried to put the button inside an update panel but it didn't work either

This is my code

Principal.Master

%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Principal.master.cs" Inherits="tp.datos.tpSolutions.Principal"  %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="css/index.css" type="text/css">
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <header>
                <div>
                    <nav class="navegacion clearfix">
                        <div class="logo">
                            <img src="img/LogoTP.png" alt="">
                        </div>
                        <div class="conten-iconos clearfix">
                            <li class="icono"><a href="#Alerts"><i class="material-icons">notifications</i></a></li>
                            <li class="icono"><a href="#Help"><i class="material-icons">help</i></a></li>
                            <li class="dropdown icono">
                                <a
                                    href="#UserMenu"
                                    class="dropdown-toggle"
                                    data-toggle="dropdown"
                                    role="button"
                                    aria-haspopup="true"
                                    aria-expanded="false">
                                    <i class="material-icons user-icon">person</i>
                                </a>
                                <ul class="dropdown-menu">
                                  <li>
                                      <strong>
                                        <asp:label ID="Saludo" runat="server" style="color:black"></asp:label>
                                      </strong>
                                  </li>
                                 <%--<li><a href="#PlanName"><em>Plan Name</em></a></li>--%>
                                  <li role="separator" class="divider"></li>
                                  <li><a href="cambioclave/cambioclave.aspx">Cambio Clave</a></li>
                                <%--<li><a href="#Preferences">Preferences</a></li>--%>
                                  <%--<li><a href="#Billing">Billing</a></li>--%>
                                 <%-- <li role="separator" class="divider"></li>--%>
                                  <li><a href="#Logout">Logout</a></li>
                                </ul>
                            </li>
                        </div>
                        </nav>
                      </div>
                 </header>
                </div>
                 <div class="contenedorFormularrio clearfix">
                    <div class="contenedor-menu clearfix">
                        <div class="clearfix menu">
                            <nav>
                                <asp:Panel class="acordeon" ID="listMenu" runat="server"></asp:Panel>                     
                            </nav>
                        </div>
                    </div>
                     <div class="conten-formulario">
                        <div class="conten-opciones">
                        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                         </asp:ContentPlaceHolder>
                     </div>
                 </div>
                  </div>         
    </form>
</body>
</html>

Principal.Master.cs

    public partial class Principal : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fillMenu();
            }
        }


        public void fillMenu()
        {
            StringBuilder sb = new StringBuilder();
            DataTable dtMenuParent = findParent();
            DataTable dtMenuChild = findChild();
            // 
            try
            {
                if (dtMenuParent!= null)
                {
                    sb.AppendLine("<ul>");
                    foreach (DataRow menuItem in dtMenuParent.Rows)
                    {
                        string menuId = menuItem["id"].ToString();
                        string menuName = menuItem["MenuParent"].ToString();

                        sb.Append("<li class = 'clearfix'><a href='#"+"'>" + menuName + "</a>");


                        DataRow[] childMenu = dtMenuChild.Select(String.Format("id_parent='" + menuItem["id"] + "'"));
                        foreach (DataRow subMenuItem in childMenu)
                        {
                            string subMenu = subMenuItem["MenuChild"].ToString();
                            string url = subMenuItem["ChildMenu_URL"].ToString();
                            sb.Append("<ul><li class='sub-menu'><a href='" + url + "'>" + subMenu + "</a></li></ul>");
                        }
                        sb.Append("</li>");
                    }
                   
                    sb.Append("</ul>");
                    listMenu.Controls.Add(new LiteralControl(sb.ToString()));
                }
            
               
            }
            catch (Exception ex)
            {
                ClsMetodosLogica.LogError(ex);
            }
        }

        // Buscar padres
        public DataTable findParent()
        {
            DataTable dtParent = new DataTable();
            string query = "SELECT id,MenuParent FROM tb_MenuWebParent";
            try
            {
                using (SqlConnection con = new SqlConnection(ClsConexion.cadenaConexion))
                {
                    using (SqlCommand command = new SqlCommand(query,con))
                    {
                        con.Open();
                        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query,con);
                        sqlDataAdapter.Fill(dtParent);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return dtParent;
        }

        // Buscar hijos
        public DataTable findChild()
        {
            DataTable dtChild = new DataTable();
            string query = "SELECT id, id_parent,MenuChild,ChildMenu_URL FROM tb_MenuWebChild";
            try
            {
                using (SqlConnection connection = new SqlConnection(ClsConexion.cadenaConexion))
                {
                    using (SqlCommand command = new SqlCommand(query,connection))
                    {
                        connection.Open();
                        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connection);
                        sqlDataAdapter.Fill(dtChild);
                    }
                }
            }
            catch (Exception ex)
            {
                ClsMetodosLogica.LogError(ex);                
            }

            return dtChild;              
        }
    }

Default.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Principal.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="tp.datos.tpSolutions.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:FileUpload ID="Upload" runat="server" Width="678px"  Enabled="true" EnableTheming="True" />
    <br />
    <br />
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
     <asp:UpdatePanel runat="server" id="UpdatePanel" UpdateMode="Conditional" ChildrenAsTriggers="true">
         <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnVisualizarArchivo" EventName="Click" />
        </Triggers>
         <ContentTemplate>
               <asp:Button ID="btnVisualizarArchivo"  class="btnButton" runat="server" Text="Visualizar" OnClick="btnVisualizarArchivo_Click"/>
               <asp:Button ID="btnCargarArchivo" class="btnButton" runat="server" Text="Cargar" OnClick="btnCargarArchivo_Click" />
         </ContentTemplate>
     </asp:UpdatePanel>
    <br />
    <br />
    <br />
    <div class="scrolling-table-container" >
        <asp:GridView ID="grdArchivo" runat="server" Width="897px" AutoGenerateColumns="true" class="mGrid" HeaderStyle-HorizontalAlign="Center" 
            RowStyle-HorizontalAlign="Center" RowStyle-Wrap="true" BorderStyle="None" BorderWidth="1px" HorizontalAlign="Center" ClientIDMode = "Static" CssClass="gridViewStyle"  >
        </asp:GridView>
    </div>
</asp:Content>

Defautl.aspx.cs

 

public partial class Default : System.Web.UI.Page
    {
        Principal principal = new Principal();
        public static DataTable dtDatos = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        public DataTable visualizarArchivo()
        {
            dtDatos = new DataTable();

            try
            {
                if (Upload.PostedFile.FileName == "")
                {
                    Response.Write("<script>alert('Seleccione un archivo');</script>");
                }
                else
                {
                    // Validar extensión del archivo 
                    string ext = Path.GetExtension(Upload.PostedFile.FileName);
                    switch (ext.ToLower())
                    {
                        case ".txt":

                            //DataTable dtTxt = new DataTable();
                            using (StreamReader sr = new StreamReader(Upload.FileContent))
                            {

                                string[] headers = sr.ReadLine().Split('\t');
                                foreach (string header in headers)
                                {
                                    dtDatos.Columns.Add(header);
                                }
                                while (!sr.EndOfStream)
                                {
                                    string[] rows = sr.ReadLine().Split('\t');
                                    DataRow dr = dtDatos.NewRow();
                                    for (int i = 0; i < headers.Length; i++)
                                    {
                                        dr[i] = rows[i];
                                    }
                                    dtDatos.Rows.Add(dr);
                                }

                                grdArchivo.DataSource = dtDatos;
                                grdArchivo.DataBind();
                            }
                            break;
                        case ".csv":
                            // DataTable dtCsv = new DataTable(); 
                            using (StreamReader sr = new StreamReader(Upload.FileContent))
                            {

                                string[] headers = sr.ReadLine().Split(';');
                                foreach (string header in headers)
                                {
                                    dtDatos.Columns.Add(header);
                                }
                                while (!sr.EndOfStream)
                                {
                                    string[] rows = sr.ReadLine().Split(';');
                                    DataRow dr = dtDatos.NewRow();
                                    for (int i = 0; i < headers.Length; i++)
                                    {
                                        dr[i] = rows[i];
                                    }
                                    dtDatos.Rows.Add(dr);
                                }

                                grdArchivo.DataSource = dtDatos;
                                grdArchivo.DataBind();
                            }

                            break;
                        default:
                            Response.Write("<script>alert('Archivo no permitido');</script>");
                            break;
                    }
                }
            }
            catch (Exception ex)
             {
                throw ex; 
            }
            return dtDatos;
        }


        private bool UploadFile()
        {
            bool bandera = false;
            try
            {
                if (Upload.HasFile)
                {
                    string filename = Path.GetFileName(Upload.FileName);
                    Upload.SaveAs(Server.MapPath("~/Archivos/") + filename);
                   
                    bandera = true;
                }
                else
                {
                    bandera = false;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return bandera;
        }

      
        protected void btnVisualizarArchivo_Click(object sender, EventArgs e)
        {
            if (UploadFile())
            {
                btnCargarArchivo.Enabled = true;
            }
            visualizarArchivo();
        }

    }

SQL TABLES

tb_MenuWebParent

id            MenuParent

1             WorkForce

2             Conjuntos

3             Reporting

tb_ MenuWebChild

id            id_parent           MenuChild         ChildMenu_URL

1             1             HeadCount        Default.aspx

2             2             Crear Conjunto CConjuntos.aspx

2             3             Crear     Default.aspx

 

What is the correct way to use a button within an update panel? Or how can I solve this problem?

You are viewing reply posted by: pandeyism 23 days ago.
Posted 23 days ago

Hi fredo1094,

You need remove is not postback code from master page.

Refer below sample.

HTML

MasterPage.master

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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></title>
    <link href="StyleSheet.css" rel="stylesheet" />
    <style type="text/css">
        @font-face
        {
            font-family: 'Material Icons';
            font-style: normal;
            font-weight: 400;
            src: url(https://fonts.gstatic.com/s/materialicons/v48/flUhRq6tzZclQEJ-Vdg-IuiaDsNa.woff) format('woff');
        }
        
        .material-icons
        {
            font-family: 'Material Icons';
            font-weight: normal;
            font-style: normal;
            font-size: 24px;
            line-height: 1;
            letter-spacing: normal;
            text-transform: none;
            display: inline-block;
            white-space: nowrap;
            word-wrap: normal;
            direction: ltr;
            -moz-font-feature-settings: 'liga';
            -moz-osx-font-smoothing: grayscale;
        }
    </style>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
            <header>
                <div>
                    <nav class="navegacion clearfix">
                        <div class="logo">
                            <img src="img/LogoTP.png" alt="">
                        </div>
                        <div class="conten-iconos clearfix">
                            <li class="icono"><a href="#Alerts"><i class="material-icons">notifications</i></a></li>
                            <li class="icono"><a href="#Help"><i class="material-icons">help</i></a></li>
                            <li class="dropdown icono">
                                <a
                                    href="#UserMenu"
                                    class="dropdown-toggle"
                                    data-toggle="dropdown"
                                    role="button"
                                    aria-haspopup="true"
                                    aria-expanded="false">
                                    <i class="material-icons user-icon">person</i>
                                </a>
                                <ul class="dropdown-menu">
                                  <li>
                                      <strong>
                                        <asp:label ID="Saludo" runat="server" style="color:black"></asp:label>
                                      </strong>
                                  </li>
                                  <li role="separator" class="divider"></li>
                                  <li><a href="cambioclave/cambioclave.aspx">Cambio Clave</a></li>
                                  <li><a href="#Logout">Logout</a></li>
                                </ul>
                            </li>
                        </div>
                        </nav>
                      </div>
                 </header>
        </div>
        <div class="contenedorFormularrio clearfix">
            <div class="contenedor-menu clearfix">
                <div class="clearfix menu">
                    <nav>
                                <asp:Panel class="acordeon" ID="listMenu" runat="server"></asp:Panel>                    
                            </nav>
                </div>
            </div>
            <div class="conten-formulario">
                <div class="conten-opciones">
                    <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                    </asp:ContentPlaceHolder>
                </div>
            </div>
        </div>
    </div>
    </form>
</body>
</html>

Default.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
    <asp:FileUpload ID="Upload" runat="server" Width="678px" />
    <br />
    <br />
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel runat="server" ID="UpdatePanel" UpdateMode="Conditional" ChildrenAsTriggers="true">
        <Triggers>
            <asp:PostBackTrigger ControlID="btnVisualizarArchivo" />
        </Triggers>
        <ContentTemplate>
            <asp:Button ID="btnVisualizarArchivo" class="btnButton" runat="server" Text="Visualizar"
                OnClick="btnVisualizarArchivo_Click" />
            <asp:Button ID="btnCargarArchivo" class="btnButton" runat="server" Text="Cargar"
                OnClick="btnCargarArchivo_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <br />
    <br />
    <br />
    <div class="scrolling-table-container">
        <asp:GridView ID="grdArchivo" runat="server" AutoGenerateColumns="true">
        </asp:GridView>
    </div>
</asp:Content>

Namespaces

using System.Data;
using System.IO;

Code

MasterPage.master.cs

protected void Page_Load(object sender, EventArgs e)
{
    fillMenu();
}

public void fillMenu()
{
    StringBuilder sb = new StringBuilder();
    DataTable dtMenuParent = findParent();
    DataTable dtMenuChild = findChild();
    //
    try
    {
        if (dtMenuParent != null)
        {
            sb.AppendLine("<ul>");
            foreach (DataRow menuItem in dtMenuParent.Rows)
            {
                string menuId = menuItem["id"].ToString();
                string menuName = menuItem["MenuParent"].ToString();
                sb.Append("<li class = 'clearfix'><a href='#" + "'>" + menuName + "</a>");
                DataRow[] childMenu = dtMenuChild.Select(String.Format("id_parent='" + menuItem["id"] + "'"));
                foreach (DataRow subMenuItem in childMenu)
                {
                    string subMenu = subMenuItem["MenuChild"].ToString();
                    string url = subMenuItem["ChildMenu_URL"].ToString();
                    sb.Append("<ul><li class='sub-menu'><a href='" + url + "'>" + subMenu + "</a></li></ul>");
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");
            listMenu.Controls.Add(new LiteralControl(sb.ToString()));
        }
    }
    catch (Exception ex)
    {

    }
}

public DataTable findParent()
{
    DataTable dtParent = new DataTable();
    dtParent.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof(int)), new DataColumn("MenuParent", typeof(string)) });
    dtParent.Rows.Add(1, "WorkForce");
    dtParent.Rows.Add(2, "Conjuntos");
    dtParent.Rows.Add(3, "Reporting");
    return dtParent;
}

public DataTable findChild()
{
    DataTable dtChild = new DataTable();
    dtChild.Columns.AddRange(new DataColumn[] { new DataColumn("id", typeof(int)), new DataColumn("id_parent", typeof(int)), new DataColumn("MenuChild", typeof(string)), new DataColumn("ChildMenu_URL", typeof(string)) });
    dtChild.Rows.Add(1, 1, "HeadCount", "Default.aspx");
    dtChild.Rows.Add(2, 2, "Crear Conjunto", "CConjuntos.aspx");
    dtChild.Rows.Add(2, 3, "Crear", "Default.aspx");
    return dtChild;
}

Default.aspx.cs

public static DataTable dtDatos = new DataTable();
public DataTable visualizarArchivo()
{
    dtDatos = new DataTable();
    try
    {
        if (Upload.PostedFile.FileName == "")
        {
            Response.Write("<script>alert('Seleccione un archivo');</script>");
        }
        else
        {
            string ext = Path.GetExtension(Upload.PostedFile.FileName);
            switch (ext.ToLower())
            {
                case ".txt":
                    using (StreamReader sr = new StreamReader(Upload.FileContent))
                    {
                        string[] headers = sr.ReadLine().Split('\t');
                        foreach (string header in headers)
                        {
                            dtDatos.Columns.Add(header);
                        }
                        while (!sr.EndOfStream)
                        {
                            string[] rows = sr.ReadLine().Split('\t');
                            DataRow dr = dtDatos.NewRow();
                            for (int i = 0; i < headers.Length; i++)
                            {
                                dr[i] = rows[i];
                            }
                            dtDatos.Rows.Add(dr);
                        }
                        grdArchivo.DataSource = dtDatos;
                        grdArchivo.DataBind();
                    }
                    break;
                case ".csv":
                    using (StreamReader sr = new StreamReader(Upload.FileContent))
                    {
                        string[] headers = sr.ReadLine().Split(';');
                        foreach (string header in headers)
                        {
                            dtDatos.Columns.Add(header);
                        }
                        while (!sr.EndOfStream)
                        {
                            string[] rows = sr.ReadLine().Split(';');
                            DataRow dr = dtDatos.NewRow();
                            for (int i = 0; i < headers.Length; i++)
                            {
                                dr[i] = rows[i];
                            }
                            dtDatos.Rows.Add(dr);
                        }
                        grdArchivo.DataSource = dtDatos;
                        grdArchivo.DataBind();
                    }
                    break;
                default:
                    Response.Write("<script>alert('Archivo no permitido');</script>");
                    break;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return dtDatos;
}

private bool UploadFile()
{
    bool bandera = false;
    try
    {
        if (Upload.HasFile)
        {
            string filename = Path.GetFileName(Upload.FileName);
            Upload.SaveAs(Server.MapPath("~/Archivos/") + filename);
            bandera = true;
        }
        else
        {
            bandera = false;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return bandera;
}

protected void btnVisualizarArchivo_Click(object sender, EventArgs e)
{
    if (UploadFile())
    {
        btnCargarArchivo.Enabled = true;
    }
    visualizarArchivo();
}
protected void btnCargarArchivo_Click(object sender, EventArgs e)
{

}

Screenshot