Search code examples
c#asp.netasp.net-ajaxmodalpopupextender

ASP.NET passing a function return value from a modalpopupextender to the main form


I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.

I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.

However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.

The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.

Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.

What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.

This is the aspx page

<%@ Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="Scripts/local.js"></script>
    <script type="text/javascript">
        function callme(thisone)
          {
                $("#ddlStores").prop('disabled', false);
          }

</script>
    <div>
        <table style="width: 500px">
            <tr>
                <td>
                    <asp:Label ID="lblMessage" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
                        <asp:ListItem Value="0">Select Store</asp:ListItem>
                        <asp:ListItem Value="10101">Parkseed</asp:ListItem>
                        <asp:ListItem Value="10151">Wayside</asp:ListItem>
                        <asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
                    <asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    **<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
                </td>
            </tr>
        </table>
        <asp:HiddenField ID="hdnFilename" runat="server" />
    </div>

    <asp:UpdatePanel id="updVerifyChoice" runat="server">
        <ContentTemplate>
                <div style="display: none;">
                    <asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
                    <%--Dummy Button added to assign the target controlid of PopupExtender--%>
                    <asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
                </div>
                    <asp:Panel ID="pnlVerifyRequestPopup" runat="server">

                        <div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
                            <table style="background-color: #F7F5F4; width: 300px;">
                                <tr>
                                    <td><label>Verify Process Request</label></td>
                                    <td style="text-align: right;">
                                        <label class="lbl_3">
                                            <asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
                                                runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width: 150px;" colspan="2">
                                        <asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" class="align_right">
                                        <asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
                                            OnClick="btnPopVerify_Click" />
                                    </td>
                                </tr>
                            </table>
                            <asp:HiddenField ID="hdnReturnData" runat="server" />
                        </div>
                    </asp:Panel>
                <ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
                    TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
                </ajax:ModalPopupExtender>

             </ContentTemplate>
        </asp:UpdatePanel>
</asp:Content>

The field in question that should get the returned values from the function is called txtResults.

Here is the c# code (I cut out unneeded code)

namespace OrderManager
{
    public partial class ProductRankLoader : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];

//            Session.Add("returnText", "");

            var header = Master.FindControl("lblpageheading") as Label;
            header.Text = "Product Rank Loader";

            if (IsPostBack)
            {
                try
                {

                    //if (Session["Verified"].ToString() != "")
                    //{
                        Session["returnText"] = doProcess();
                        if (Session["returnText"].ToString() != "")
                        {
                            txtResults.Text = Session["returnText"].ToString();
                            lblMessage.Text = "";
                        }

                    //}

                }
                catch { }
            } else
            {
                Session.Add("returnText", "");
                Session.Add("Verified", "");
            }
        }

        protected void btnProcess_Click(object sender, EventArgs e)
        {

            Boolean fileOK = false;
            string filename = Path.GetFileName(fulRanks.FileName);
            hdnFilename.Value = filename;

            if (fulRanks.HasFile)
            {
                ddlStores.Enabled = true;
                String fileExtension =
                    System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
                String[] allowedExtensions = { ".txt", ".log" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                        fulRanks.SaveAs(@"c:\temp\" + filename);
                    }
                }
            }

            if (!fileOK || ddlStores.SelectedIndex <= 0)
            {
                lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
                return;
            } else { }

            lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
            Session.Add("Verified", "true");
            extVerifyProcess.Show();

        }

        protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
        {
            Session["Verified"] = "";
            Session["returnText"] = "";
            Response.Redirect("ProductRankLoader.aspx");
        }
        protected void btnPopVerify_Click(object sender, EventArgs e)
        {
            //Session["returnText"] = doProcess();
            Session.Remove("returnText");
            Session.Remove("Verified");
        }
        private string doProcess()
        {
            string tmpResults = "";
            Int32 store = 0;
            if (ddlStores.SelectedIndex > 0)
            {
                Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
                string filename = hdnFilename.Value;

                ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);

                List<string> results = newRanks.ProcessRanks();
                foreach (string result in results)
                {
                    tmpResults += result + '\r';
                }
               // txtResults.Text = tmpResults;
                lblMessage.Text = "";
            }
            else
            {
                lblMessage.Text = "";
            }
            return tmpResults;
        }

        protected void btnDummy_Click(object sender, EventArgs e)
        {

        }
    }
}

Solution

  • If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:

    $('#lBtnVerifyRequestClose').click(function (event) {
        event.preventDefault();
        $('#pnlVerifyRequestPopup').dialog('close');
    });
    

    the event.preventDefault() ensure that postback are not executed. If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.