Incorporating an ASP.Net button through backend coding

I have a sleek form with an AJAX Accordion pane. I am using a Master page, but the ASPX child page is structured like this:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  <link rel="stylesheet" href="Content/themes/base/jquery-ui.css">
  <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>  
  <script src="Scripts/jquery-ui-1.8.24.min.js" type="text/javascript"></script>  

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server">

    <asp:UpdatePanel ID="MyUpdatePanel" runat="server">
        <ContentTemplate>
            <asp:panel ID="MyContent" runat="server">

    <!--  ************************************  -->
                    <ajaxtoolkit:modalpopupextender id="MdlCommentsExtender" runat="server"     
                        targetcontrolid="MyContent" popupcontrolid="pnlComments" 
                        popupdraghandlecontrolid="PopupHeader" drag="True" 
                        backgroundcssclass="ModalPopupBG" Enabled="False"  >
                    </ajaxtoolkit:modalpopupextender>

                    <asp:panel id="pnlComments" style="display: none" runat="server" BackColor="White" CssClass="modalPopup">
                        <div class="HellowWorldPopup">
                            <div class="PopupHeader" id="Div3" style="border: thin solid #000000; vertical-align: middle; text-align: center; background-color: #C0C0C0; color: #000000; font-weight: bold; height: 40px;" ><br />Pend Comment</div>
                                <div class="PopupBody" style="background-color: #FFFFFF">
                                    <table style="width: 300px">
                                        <tr style="text-align:left">
                                            <td style="padding:4px"><asp:Label ID="lblCommentBox" runat="server" Text="Comment:"></asp:Label></td>
                                        </tr>
                                        <tr>
                                            <td style="padding:4px">
                                           <asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server"  onkeyup="textCounter(this, this.form.remLen, 50);" onkeydown="textCounter(this, this.form.remLen, 50);" onpaste="textCounter(this, this.form.remLen, 50);" />
                                            </td>
                                        </tr>  
                                        <tr>
                                            <td>
                                                <input readonly="readonly" type="text" id="remLen" name="remLen" size="2" maxlength="3" value="50" /> characters left
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="Controls">
                                    <table style="width: 300px">
                                        <tr>
                                           <td style="vertical-align: middle; text-align: center"> <asp:Button ID="mdlCmntsOk_Click" runat="server" Text="OK" CssClass="textbox" Height="28px" Width="75px" OnClick="mdlCommentsOk_Click" /></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>  
                    </asp:panel>
            </asp:panel>
        </ContentTemplate>
    </asp:UpdatePanel>

    <!--  ************************************  -->

</asp:Content>

This setup includes a modalpopupextender that I want to trigger from an "Edit" button. The Accordion is dynamically added via code-behind. My entire code-behind script appears as follows:

public partial class frmBenefitSummaryList : System.Web.UI.Page
{
    string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnCST"].ConnectionString;


    protected void Page_Load(object sender, EventArgs e)
    {

        BindAccordions();
        if (Page.IsPostBack)
        {
            MdlCommentsExtender.Show();
        }
    }

    private void BindAccordions()
    {
        #region Get the value from the database

         DataTable dt = new DataTable();   
         try   
         {   

             using (SqlConnection connection = new SqlConnection())   
             {
                 connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnCST"].ToString();   
                 connection.Open();   
                 SqlCommand cmd = new SqlCommand();   
                 cmd.Connection = connection;
                 string CmdTxt = "Select CBL.ID, CBL.[Category], CBL.[Provision], CTL.MarkForReview, CTL.IssueType, CTL.Resolution, CTL.Feedback, CTL.TemplateID";
                 CmdTxt = CmdTxt + " from [tblCSTBenefitList] CBL";
                 CmdTxt = CmdTxt + " LEFT JOIN tblCSTTemplateList CTL";
                 CmdTxt = CmdTxt + " ON CBL.ID = CTL.BenefitID";
                 CmdTxt = CmdTxt + " where CBL.ID > '0'";
                 CmdTxt = CmdTxt + " ORDER BY CBL.[Category], CBL.[Provision] ASC";

                 cmd.CommandText = CmdTxt; 
                 cmd.CommandType = CommandType.Text;   
                 SqlDataAdapter da = new SqlDataAdapter(cmd);   

                 da.Fill(dt);   
                 cmd.Dispose();   
                 connection.Close();   
             }   
         }
         catch (Exception ex) { Response.Write(ex.Message); }

        #endregion

        #region Create accordion with properties

        Accordion acrDynamic = new Accordion();
        acrDynamic.ID = "MyAccordion";
        acrDynamic.SelectedIndex = -1;//No default selection   
        acrDynamic.RequireOpenedPane = false;//no open pane   
        acrDynamic.HeaderCssClass = "accordionHeader";//Header class   
        acrDynamic.HeaderSelectedCssClass = "accordionHeaderSelected";//Selected herder class   
        acrDynamic.ContentCssClass = "accordionContent";//Content class  

        #endregion

        #region Create the panes

        Label lbTitle;   
        Label lbContent;   
        AccordionPane pane;   
        string Content = "";


        for (int i = 0; i < dt.Rows.Count; i++)   
        {
            if (Content == "")
                Content += "<table class='hoverTable'><tr><th bgcolor='#5D7B9D' width='440px'><font color='#fff'>Provision</th><th bgcolor='#5D7B9D' width='120px'><font color='#fff'>Mark For Review</th><th bgcolor='#5D7B9D' width='120px'><font color='#fff'>Issue Type</th><th bgcolor='#5D7B9D' width='120px'><font color='#fff'>Resolution</th><th bgcolor='#5D7B9D' width='120px'><font color='#fff'>Feedback</th><th bgcolor='#5D7B9D' width='60px'><font color='#fff'>Edit</th></tr>";

            string BranchName = dt.Rows[i]["Category"].ToString();   
            string Next_Branch = "";   

            if (i != dt.Rows.Count - 1)   
                Next_Branch = dt.Rows[i + 1]["Category"].ToString();

            Content += "<tr>";
            Content += "<td>" + dt.Rows[i]["Provision"].ToString() + "</td>";
            Content += "<td>" + dt.Rows[i]["MarkForReview"].ToString() + "</td>";
            Content += "<td>" + dt.Rows[i]["IssueType"].ToString() + "</td>";
            Content += "<td>" + dt.Rows[i]["Resolution"].ToString() + "</td>";
            Content += "<td>" + dt.Rows[i]["Feedback"].ToString() + "</td>";
            Content += "<td><input type=\"submit\" ID=\"btnEdit\" name=\"ctl00$MainContent$btnEdit_OnClick\" onserverclick=\"btnEdit_OnClick()\" UseSubmitBehavior=\"False\" value=\"Edit\" /></td>";
            Content += "</tr>"; 

            if (BranchName != Next_Branch) //if last row of branch   
            {
                Content += "</table>";
                pane = new AccordionPane();   
                lbTitle = new Label();   
                lbContent = new Label();   
                pane.ID = "Pane_" + BranchName.ToString();   
                lbTitle.Text = BranchName;   
                pane.HeaderContainer.Controls.Add(lbTitle);   
                lbContent.Text = Content;   
                pane.ContentContainer.Controls.Add(lbContent);   
                acrDynamic.Panes.Add(pane);   
                Content = "";   
            }
        }

        #endregion

        #region Add the accordion to the page

        MyContent.Controls.Add(acrDynamic);

        #endregion

    }

    protected void btnEdit_OnClick(object sender, EventArgs e)
    {
        MdlCommentsExtender.Enabled = true;
        MdlCommentsExtender.Show();
        ScriptManager.GetCurrent(this).SetFocus(this.txtCommentBox);
    }

    protected void mdlCommentsOk_Click(object sender, EventArgs e)
    {
        MdlCommentsExtender.Hide();
    }
}

That's my complete code structure. It works perfectly, except for one thing: the current Edit button triggers a postback, which interferes with my modal form. I need to change it to an asp:Button to activate my modal window.

Could someone please provide me with guidance on how to achieve this? Assume I need detailed instructions and explanations as I am not very familiar with coding. Thank you!

Answer №1

When working with code-behind in ASP.NET, it's best to avoid creating HTML markup directly. Instead, focus on regenerating the control tree on page load. Here's an example of how you can achieve this:

Table table = null;

string BranchName = null;

for (int i = 0; i < dt.Rows.Count; i++)
{
    TableRow tr;
    if (BranchName != dt.Rows[i]["Category"].ToString())
    {
        BranchName = dt.Rows[i]["Category"].ToString();
        
        // Setup accordion pane
        AccordionPane pane = new AccordionPane();
        acrDynamic.Panes.Add(pane);

        // Pane content
        Label lbTitle = new Label();
        pane.ID = "Pane_" + BranchName;
        lbTitle.Text = BranchName;
        pane.HeaderContainer.Controls.Add(lbTitle);

        // Table within the pane container
        table = new Table();
        table.CssClass = "hoverTable";
        pane.ContentContainer.Controls.Add(table);

        // Top row headers
        tr = new TableRow();
        TableHeaderCell th = new TableHeaderCell();
        th.Width = 440;
        th.Text = "Provision";
        tr.Controls.Add(th);
        th = new TableHeaderCell();
        th.Width = 120;
        th.Text = "Mark for Review";
        tr.Controls.Add(th);
        table.Controls.Add(tr);
    }

    // Add data rows and buttons
    tr = new TableRow();
    TableCell tc = new TableCell();
    tc.Text = dt.Rows[i]["Provision"].ToString();
    tr.Controls.Add(tc);
    tc = new TableCell();
    tc.Text = dt.Rows[i]["MarkForReview"].ToString();
    tr.Controls.Add(tc);
    
    Button button = new Button();
    button.Text = "Edit";
    button.UseSubmitBehavior = false;
    button.Click += new EventHandler(btnEdit_OnClick);
    tc.Controls.Add(button);
    tr.Controls.Add(tc);

    table.Controls.Add(tr);
}

In terms of naming and IDs, make sure to handle that in the Render method of the Button control for a more refined result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Every time I attempt to send a PUT request using AJAX, I encounter an error

After developing HTML and AJAX code to update a camera password within my network, I encountered an issue upon form submission. "error" (net::ERR_EMPTY_RESPONSE) Surprisingly, the PUT request functions perfectly when tested with POSTMAN, showing a stat ...

The session name has not been properly defined

Sorry for any errors in translation. I'm facing an issue where the session name I insert is coming up as undefined. However, when I manually enter the username, everything works fine. View Image <? php session_start (); echo var_dump ($ _SESSION ...

The function appears to be failing to execute

I'm currently working on a dynamic search bar using AJAX to retrieve results from a database. I've noticed that when I check in the debugger, the code isn't triggering the handleSuggest() function which is responsible for updating the inner ...

Unveiling the Power of KnockoutJS: Displaying HTML Content and Populating

I am trying to achieve a unique effect using KnockoutJS. Let's consider a basic model: var Item = function () { var self = this; self.title = ko.observable(""); }; In addition, I have a ViewModel: var ItemList = function () { var self = ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

AngularJS Vimeo API Request Error: "401 Authorization Required"

I've been experimenting with making external API calls to Vimeo from my AngularJS code using $http.jsonp. However, I keep receiving a 401 Authorization required error even though I have included my authorization key in the header. I encountered a simi ...

Implementing Pessimistic Locking in PHP/MySQL Using jQuery

As I consider implementing record locking for an application I'm involved in, a challenge arises with users spending hours editing records. This often leads to conflicts when someone else attempts to make changes simultaneously, especially since there ...

What could be causing jQuery to overlook dynamically loaded jQuery Mobile buttons?

While working with a web page that uses jQuery Mobile, I utilized Ajax to load the following HTML content. The key detail is the presence of the onButton class attached to the anchor tag. <a class="onButton ui-btn ui-btn-inline ui-btn-corner-all ui-sha ...

Web API Implementation of Null-Safe Empty List Handling

I have a scenario where an angular controller is making a POST request to a web API method. I attempted to implement null safety with the IEnumerable, but it ended up causing the IEnumerable to always be empty. Here is the angular call: $http.post(custom ...

Shut down Chrome Web Driver when closing the Windows Form

I have a simple query that I've been struggling to find an answer for. Every time I try to close my Windows Form with the Selenium Chrome Web driver running, it shuts down the application but leaves the Chrome console and browser open. Is there a way ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

Fetching a Wikipedia page using AJAX or the fetch() method

I am currently attempting to dynamically retrieve a Wikipedia webpage within the browser in order to utilize XSLTProcessor for further processing of the XHTML content. Unfortunately, my efforts have been unsuccessful as Wikipedia is not sending the necess ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

The ASP.Net ajax file submission model appears to be empty, even though the individual variables are functioning correctly

I am facing an issue while trying to upload a file using ajax. When attempting to receive a model, it is empty; however, if I try to obtain separate values, it works fine. public ActionResult UploadImage(HttpPostedFileBase File, string UniqueCode) { // ...

Employ a separate function to extract HTML content from a jQuery target in an AJAX response

Initially, the HTML div is empty upon loading the page. However, clicking a button triggers jQuery AJAX to load new HTML content into the div. $("#control-list a#ms").click(function(){ var postData = "actionrequest=ms"; $.ajax({url:"SSSutility.php ...

Troubleshooting and resolving issues with ColdFusion CFC's JSON data retrieval

On my development and production servers, both running IIS7 and Coldfusion 8 Standard, I encountered an issue with the website's SSL configuration. While the entire website is on SSL in production, except for the login page, I was working on a site s ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...

PHP Ajax request to the same PHP script resulted in a response of null

As part of my development process, I am creating a single-page script called category.php to handle category management. This script includes an input button that triggers an AJAX call. <input type="button" id="btn" /> The jQuery code is u ...

The change event for the select element is malfunctioning

Currently, I am deep diving into Nodejs with the second edition of the node cookbook. This book has caught my attention because it explains concepts using practical sample code, making it easier to grasp. The example code I am working on is related to Br ...

Regular Expression for valid Mobile Phone Number country code starting with 0092 or +92

Have you come across a standardized regular expression that captures all valid mobile phone numbers, such as 00923465655239 or +923005483426? I've been searching for it for two days but haven't found an expression that fits these formats. The co ...