Link to home
Start Free TrialLog in
Avatar of skaleem1
skaleem1Flag for Canada

asked on

Multiple Ajax calls on the same page, first not firing when the page is accessed by Response.Redirect

I have an aspx page with the following two ajax calls  (see the code section under Javascript/ajax heading). I have a popup extender that has two html select controls that I am filling with data utilizing these ajax calls. When the page initially loads, it calls the function pageLoad within the javascript (see code section under Javascript/ajax heading) and this function makes the ajax calls through the two urls pointing to an http handler class (see the code in the code section under http handler class heading) to fetch data from the urls. All works fine when the data is initially loaded. The issues come when the button btnAddPart is clicked and the modal popup is opened with both the html select list boxes correctly populated with data. Issue is that when the button btnAddPartToPortfolioSave is clicked, it saves the data in the database and again makes the two ajax calls however the first call does not go though while the second one goes through. I tried to debug and found out that the firat ajax call does not take me inside the http handler class to get the data from the database while the second one does. Can you please view and figure out why the first ajax call is not firing while the second one does. Please note that everything works fine when I load the data initially. This issue only conmes when I try to save the data by using the save button on the popup and try to force the postback through the following line of code as well as using the response.redirect in the save button click event. I think the issue can be resolved only by looking into the code in detail.

btnAddPartToPortfolioSave.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}')", btnAddPartToPortfolioSave.UniqueID, "", "PortfolioPartsAdded");

and the fnClickOK function in the javascript section below forces a postback and then the save method of the button click redirects back to the same page to kind of force the two ajax calls again.

I would appreciate if you please review the code in detail and try to understand my question.
In short the issue is:
The two ajax calls are correctly run one by one and fetch data to fill the html select controls when the page initially loads. However, when the modal popup is opened and the data in the html select control is saved by clicking the save button on the popup panel, the page loaded by response.redirect behaves differently from the first load. It rather does not make the first ajax call and only makes the second call correctlly. What needs to be changed in this  scenario to successfully complete both ajax calls.
Thanks.
Javascript/ajax:

<script type="text/javascript">
    
     //Gets the browser specific XmlHttpRequest Object
        function getXmlHttpRequestObject() 
        {	
            if (window.XMLHttpRequest) 
            {		
                return new XMLHttpRequest(); //Not IE	
            } 
            else if(window.ActiveXObject) 
            {		
                return new ActiveXObject("Microsoft.XMLHTTP"); //IE	
            } 
            else 
            {		
                //Display your error message here and inform the user they might want to upgrade their browser.		
                alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade your browser.");	
            }
         }
         
         //Get our browser specific XmlHttpRequest object.
         var receiveReq = getXmlHttpRequestObject();
         //alert(receiveReq);
         var DataReturned;
         var AjaxSecondCallCompleted="False";
         
        function pageLoad(sender,args) 
        { 
                if(AjaxSecondCallCompleted=="True")
                    AjaxSecondCallCompleted="False"
                DataReturned="AllParts";
                getPortfolioParts();
            
        }
        
        
         function getPortfolioParts() 
         {
            switch(DataReturned)
            {
            case "AllParts":
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                alert(CurrentPortfolio);
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio);
                alert(url);
                break;
            case "CurrentPortfolioParts":
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio) ;
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
            }  
            
            
             receiveReq.abort();
                
             receiveReq.open("GET", url, true);
             receiveReq.onreadystatechange = updatePage;
             receiveReq.send(null);
         }

       function updatePage() 
       {
         if (receiveReq.readyState == 4) 
         {
           if (receiveReq.status == 200) 
           {alert(DataReturned);
            switch(DataReturned)
                {
                case "AllParts":
                    var elSel = document.getElementById('<% =lstAllParts.ClientID%>');
                    break;
                case "CurrentPortfolioParts":
                    var elSel = document.getElementById('<% =lstPortfolioParts.ClientID%>'); 
                    break;
                default:
                    //code to be executed if DataReturned is different from case 1 and 2
                }
                
                var response = receiveReq.responseText;
                alert(response);
                elSel.outerHTML = elSel.outerHTML.substring(0, elSel.outerHTML.indexOf('>', 0) + 1) + response + '</select>';
                
                
                if(AjaxSecondCallCompleted=="False")
                {
                    AjaxSecondCallCompleted="True"
                    DataReturned="CurrentPortfolioParts";
                    getPortfolioParts();                    
                }            
           } 
          else
             alert("status is " + receiveReq.status);
         }
       }

function fnClickOK(sender, e, Flag) 
       {
       switch(Flag)
            {
            case "Rename":
                var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                HiddenFlag.value=Flag;
                break;
            case "PortfolioPartsAdded":
                var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                HiddenFlag.value=Flag;
                //pageLoad(null, null);
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
            }  
       
          __doPostBack(sender,e); 
       }
        

http handler class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using AccessoriesApp.Biz.DataGateway;

namespace AccessoriesDBAppSolution
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AjaxDBConnectHandler : IHttpHandler
    {
        private const string PORTFOLIOPARTS = "PortFolioParts";
        string DataReturned = string.Empty;
        string CurrentPortfolioID = string.Empty;

        public void ProcessRequest(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request.QueryString["DataReturned"]))
            {
                DataReturned = context.Request.QueryString["DataReturned"];
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["CurrentPortfolio"]))
            {
                CurrentPortfolioID = context.Request.QueryString["CurrentPortfolio"];
            }
            

            context.Response.ContentType = "text/html";

            RetrieveDataGateway rdg = new RetrieveDataGateway();
            StringBuilder sb = new StringBuilder();
            DataSet dsPartsForCurrentPortfolio;

            switch (DataReturned)
            {
                case "AllParts":
                    Hashtable hshTablePartsAll = new Hashtable();
                    Hashtable hshTablePortfolioParts = new Hashtable();
                    DataSet dsDropDownPortfolios = rdg.GetDataInfoWithoutParam("GetAllAccParts");
                    dsDropDownPortfolios.Tables[0].TableName = PORTFOLIOPARTS;
                    dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", CurrentPortfolioID, "PortfolioID");

                    //foreach (DataRow row in dsDropDownPortfolios.Tables[PORTFOLIOPARTS].Rows)
                    //{
                    //    foreach (DataRow rowCurrent in dsPartsForCurrentPortfolio.Tables[0].Rows)
                    //    {
                    //        if (rowCurrent["AccPartNum"].ToString()!= row["AccPartNum"].ToString())
                    //            //sb.Append(row["AccID"].ToString() + ":" + row["AccPartNum"].ToString().Replace("'", "") + "|");
                    //            //sb.Append(string.Format("<option id='{0}'>{1}</option>", row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", "")));
                    //            sb.Append(string.Format("<option value='{0}'>{1}</option>", row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", "")));

                    //    }
                    //}
                    foreach (DataRow row in dsDropDownPortfolios.Tables[PORTFOLIOPARTS].Rows)
                    {
                        hshTablePartsAll.Add(row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", ""));
                        //sb.Append(string.Format("<option value='{0}'>{1}</option>", row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", "")));
                    }

                    List<string> ToRemove = new List<string>();

                    foreach (DataRow row in dsPartsForCurrentPortfolio.Tables[0].Rows)
                    {
                        foreach (DataColumn column in dsPartsForCurrentPortfolio.Tables[0].Columns)
                        {
                            if (column.ColumnName.ToString() == "AccPartNum")
                            {
                                for (int i = 1; i < hshTablePartsAll.Count; i++)
                                {
                                    if (hshTablePartsAll[i.ToString()].ToString() == row["AccPartNum"].ToString())
                                    {
                                        //js = js + "AddItem('" + lstPortfolioParts.ClientID + "',  '" + row["AccPartNum"].ToString().Replace("'", "") + "', '" + row["AccID"].ToString() + "'); ";
                                        //hshTablePortfolioParts.Add(row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", ""));
                                        //js = js + "RemoveItem('" + lstAllParts.ClientID + "',  '" + row["AccPartNum"].ToString().Replace("'", "") + "', '" + row["AccID"].ToString() + "'); ";
                                        //hshTablePartsAll.Remove(row["AccID"]);
                                        ToRemove.Add(row["AccID"].ToString());
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foreach (string key in ToRemove)
                    {
                        hshTablePartsAll.Remove(key);
                    }



                    for (int i = 1; i < hshTablePartsAll.Count; i++)
                    {
                        if(hshTablePartsAll[i.ToString()]!=null)
                            sb.Append(string.Format("<option value='{0}'>{1}</option>", i, hshTablePartsAll[i.ToString()].ToString().Replace("'", "")));
                    }

                    context.Response.Write(sb.ToString());

                    break;
                case "CurrentPortfolioParts":
                    dsPartsForCurrentPortfolio = null;
                    dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", CurrentPortfolioID, "PortfolioID");

                    foreach (DataRow row in dsPartsForCurrentPortfolio.Tables[0].Rows)
                    {
                        sb.Append(string.Format("<option value='{0}'>{1}</option>", row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", "")));
                    }

                    context.Response.Write(sb.ToString());

                    break;
            }

            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

aspx:

<div id="midCol" class="midCol">
        <div>&nbsp
            <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
                        </asp:ToolkitScriptManager>              
            <button id="btnAdd" type="button" runat="server" style="height:44px;width:51px"
                       onclick="ShowPopup('ModalPopupCompat');">Add</button>
            <asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="btnEdit_Click" Enabled="false" Visible="false" Height="44px" Width="51px"/>
            <asp:Button ID="btnNext" runat="server" Text="Next" Visible="false" OnClick="btnNext_Click" Height="44px" Width="51px"/>
            <asp:Button ID="btnCopy" runat="server" Text="Copy" Visible="false" OnClick="btnCopy_Click" Height="44px" Width="51px"/>&nbsp
            <asp:Button ID="btnDelete" runat="server" Enabled="false" Text="Delete" OnClick="btnDelete_Click" Height="44px" Width="51px" />
            <asp:Button ID="btnUndo" runat="server" Visible="false" Text="Undo" OnClick="btnUndo_Click" Height="44px" Width="51px"/>
            <asp:Button ID="btnRedo" runat="server" Visible="false" Text="Redo" OnClick="btnRedo_Click" Height="44px" Width="51px"/>&nbsp
            <asp:Button ID="btnReports" runat="server" Text="Reports" Visible="false" OnClick="btnReports_Click" Height="44px" Width="51px"/>&nbsp
            <asp:Button ID="btnPrint" runat="Server" Enabled="false" Text="Print" OnClick="btnPrint_Click" Height="44px" Width="51px"/>
            <asp:Button ID="btnExport" runat="Server" Enabled="false" Text="Export" OnClick="btnExport_Click" Height="44px" Width="51px"/>&nbsp
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                              
            <button id="btnCancel" type="button" runat="server" style="height:44px;width:51px">Cancel</button>
            <asp:ModalPopupExtender ID="CompatPanel_ModalPopupExtender" runat="server" 
                        TargetControlID="btnAdd" PopupControlID="CompEditPanelMain"
                        PopupDragHandleControlID="CompTitleBar" BehaviorID="ModalPopupCompat"
                        CancelControlID="btnCompCancel" OnCancelScript="cancelClickCompat();"
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true" >
                    </asp:ModalPopupExtender>                   
            <br />
            <asp:TextBox ID="text" runat="server" style="display:none;"></asp:TextBox>
         </div>
        <asp:Panel ID="PartNumberEditReadOnlyPanel" runat="server" Visible="false">
        <div>
            <table border="1">
                <tr><td class="HeaderPartDesc" bgcolor="#3366CC">
                <asp:Label ID="lblPartNumInfoHeader" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Large" Font-Bold="True"></asp:Label>&nbsp;&nbsp;<asp:Label ID="lblPartDescInfoHeader" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td></tr>
            </table>
        </div>
        </asp:Panel>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <fieldset style="width:700px">
        <div>           
            <table><tr><td>
            <asp:Label ID="lblPortfolio" runat="server" Text="Portfolio:"></asp:Label>&nbsp;
            <asp:DropDownList ID="ddlPortfolios" runat="server" Width="192px"></asp:DropDownList>&nbsp;
            <button id="btnRename" type="button" runat="server" style="height:27px;width:61px" disabled="true"
                       onclick="ShowPopup('ModalPopupRename');">Rename</button></td><td style="width:150px"></td>                       
                       <td><asp:Button ID="btnUpdatePanel" runat="server"
                        OnClick="btnUpdatePanel_Click" style="display:none;"/>
                       <asp:ModalPopupExtender ID="Rename_ModalPopupExtender" runat="server" 
                        TargetControlID="btnRename" PopupControlID="PortfolioRenamePanelMain"
                        PopupDragHandleControlID="RenameTitleBar" BehaviorID="ModalPopupRename"
                        CancelControlID="btnRenameCancel" OnCancelScript="cancelClickRename();"
                        OkControlID="btnPopupRename" OnOkScript="__doPostBack('btnPopupRename()','')" 
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true">
                    </asp:ModalPopupExtender></td>
            <td><asp:UpdatePanel ID="UpdatePanelAnimationExtender1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <fieldset style="width:150px">
            <asp:CheckBox ID="chkIsPrivate" runat="server" Text="Portfolio is private" 
                        oncheckedchanged="chkIsPrivate_CheckedChanged"/>                        
                        <br />
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:Label ID="lblPortfolioOwner" runat="server" visible="false" Text="Owner:"></asp:Label>
            </fieldset>
            </ContentTemplate>
            </asp:UpdatePanel></td></tr><tr><td></td><td style="width:150px"></td>
            <td></td></tr></table>            
            </div>
            <br /><br /><br />
            <div><asp:Button ID="btnAddPart" runat="server" Text="Add Part" style="height:23px;width:71px"
                       OnClientClick="ShowPopupAddPartToPortfolio(this); return true;"/>
            <asp:Button ID="btnAddCurrentPart" runat="server" Text="Add Current Part" OnClick="btnAddCurrentPart_Click" />
            <asp:Button ID="btnDeletePart" runat="server" Text="Remove Part" Enabled="false" OnClientClick="showConfirm(this); return true;"/>
            <asp:Label ID="lblRecordCount" runat="server" ForeColor="#990033"></asp:Label>
            <asp:Label ID="lblErrorMessageMain" ForeColor="Red" runat="server" visible="false"/>
            <asp:ModalPopupExtender ID="ConfirmDeletePanel_ModalPopupExtender" BehaviorID="mdlPopupConfirmDelete" 
                runat="server" TargetControlID="btnDeletePart" PopupControlID="DeleteConfirmPanel"
                PopupDragHandleControlID="DeleteTitleBarPanel" Drag="true"
                CancelControlID="btnNo" OnCancelScript="cancelClickConfirmDelete();"
                BackgroundCssClass="modalBackgroundDelete">
                </asp:ModalPopupExtender>
            <asp:ModalPopupExtender ID="AddPartToPortfolioPanel_ModalPopupExtender" runat="server" 
                        TargetControlID="btnAddPart" PopupControlID="AddPartToPortfolioEditPanelMain"
                        PopupDragHandleControlID="AddPartToPortfolioEditTitleBar" BehaviorID="ModalPopupAddPartToPortfolio"
                        CancelControlID="btnAddPartToPortfolioCancel" OnCancelScript="cancelClickAddPartToPortfolio();"
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true" >
                    </asp:ModalPopupExtender>                   
                </div>                          

<asp:Panel ID="AddPartToPortfolioEditPanelMain" runat="server"
                Direction="LeftToRight" CssClass="ModalWindow" style="display:none">
        <asp:Panel ID="AddPartToPortfolioEditTitleBar" runat="server">
            <table>
                <tr><td style="text-align: left; width:700px" bgcolor="#3366CC"> 
                <asp:Label ID="lblAddPartToPortfolioEditTitleBar" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Add Parts To Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label3" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td></tr>
            </table>
        </asp:Panel>
        <div class="OuterListBoxAddToPortfolio">
        <div class="InnerLeftListBox">
            <table style="width: 260px">
                <tr><td><asp:Label ID="lblForThisPartAddPartToPortfolio" runat="server" Text="Portfolio Parts" ForeColor="#3366CC" 
                Font-Size="Small" Font-Bold="True"/></td><td style="width: 30px"></td></tr>
                <tr><td style="width: 150px"><p><select id="lstPortfolioParts" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px" multiple="true" 
                onchange='OnChange("btnlstItemAddPartToPortfolioRemove", "btnlstItemAddPartToPortfolioAdd","lstPortfolioParts", "lstAllParts");'>          
                </select></p></td>
                <td style="width: 80px">
            <button id="btnlstItemAddPartToPortfolioAdd" type="button" runat="server" onclick="addSelectedItemToDestAndRemoveFromSource('btnlstItemAddPartToPortfolioAdd', 'btnlstItemAddPartToPortfolioRemove', 'lstAllParts','lstPortfolioParts');">&lt&ltAdd</button>
            <button id="btnlstItemAddPartToPortfolioRemove" type="button" runat="server" onclick="addSelectedItemToDestAndRemoveFromSource('btnlstItemAddPartToPortfolioRemove', 'btnlstItemAddPartToPortfolioAdd', 'lstPortfolioParts','lstAllParts');">Remove>></button>
            </td></tr>
            </table>
        </div>
        <div class="InnerRightListBoxAddPartToPortfolio">
            <asp:Panel ID="AddPartToPortfolioEditPanelRight" runat="server">
            </asp:Panel>
            <asp:Panel ID="AddPartToPortfolioAddPanel" runat="server">
                <table style="width: 180px">
                    <tr><td><asp:Label ID="lblAllParts" runat="server" Text="All Parts" ForeColor="#3366CC" 
                Font-Size="Small" Font-Bold="True"/></td><td style="width: 30px"></td></tr>
                    <tr><td style="width: 150px">
                    <p><select id="lstAllParts" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px" multiple="true" 
                onchange='OnChange("btnlstItemAddPartToPortfolioAdd", "btnlstItemAddPartToPortfolioRemove","lstAllParts", "lstPortfolioParts");'>          
                </select></p></td>
                    </tr>
                </table>
                
            </asp:Panel>
        </div></div>
        <br />
        <div>
       <asp:Button ID="btnAddPartToPortfolioSave" runat="server" Text="Save" OnClick="btnAddPartToPortfolioSave_Click"/>
       <asp:Button ID="btnAddPartToPortfolioCancel" runat="server" Text="Cancel" CausesValidation="False"/>
       </div>
       </asp:Panel>

Code Behind:

PageLoad Event:
btnAddPartToPortfolioSave.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}')", btnAddPartToPortfolioSave.UniqueID, "", "PortfolioPartsAdded");

if (HFlag.Value == "PortfolioPartsAdded")
            {
              HFlag.Value = "";                
              return;
            }
            

protected void btnAddPartToPortfolioSave_Click(object sender, EventArgs e)
        {
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;// ReturnDDLSelectedItem();

            txtRenamePortfolioName.Text = PortfolioNm;

            dsPortfolios = (DataSet)Session["dsPortfolios"];
            DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            string PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            rdg.DeletePortfolioPartInfo("DeletePortfolioPartInfo", int.Parse(PortfolioID.ToString()));


            SavePopupPanelData("UpdatePortfolioPartInfo", int.Parse(PortfolioID.ToString()), "PortfolioParts");

           Session["dsPortfolios"] = null;
           Response.Redirect(string.Format("~/Portfolios.aspx?calledfrom={0}", "admin"));
                        
        }

        private void SavePopupPanelData(string StoredProc, int PortfolioID, string DataSaved)
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();

            //get all values added to the listbox for this type from the hidden variable 
            string s = HDestArray.Value;

            if (s != "")
            {
                string[] ListBoxData = s.Split(',');
                foreach (string Data in ListBoxData)
                {
                    switch (DataSaved)
                    {
                        case "PortfolioParts":
                            rdg.UpdateCOOInfo(StoredProc, PortfolioID, int.Parse(Data.ToString()));
                            break;
                        default:
                            // Do nothing.
                            break;

                    }

                }
            }
        }

Open in new window

Avatar of pradyahuja
pradyahuja
Flag of Australia image

Honestly,
Dint go through all the details you posted.
but, are you trying simultaneous partial postbacks from modal popup extender??
I had a similar issue in past where I was using updatepanels and it will not handle simultaneous partial postbacks.
it is the limitation of ajaxtoolkit.


If this is what is causing the issue then I might be able to help you.
Avatar of skaleem1

ASKER

well I do have update panels as you can see in the aspx part however I am using ajax calls in the PageLoad method in javascript and I thought could be inependent of the update panel. However, that might be the case. Can you please help me with this then?
" Issue is that when the button btnAddPartToPortfolioSave is clicked, it saves the data in the database and again makes the two ajax calls"


"it saves the data" what exactly do u mean?? saves the data by making what call?
what call are u refering to?
and

"again makes the two ajax calls"

which two calls r u refering to?
please explain
ok let me explain. The popup extender panel where the btnAddPartToPortfolioSave is located, is initialized as follows with TargetControlID="btnAddPart":

<asp:ModalPopupExtender ID="AddPartToPortfolioPanel_ModalPopupExtender" runat="server"
                        TargetControlID="btnAddPart" PopupControlID="AddPartToPortfolioEditPanelMain"
                        PopupDragHandleControlID="AddPartToPortfolioEditTitleBar" BehaviorID="ModalPopupAddPartToPortfolio"
                        CancelControlID="btnAddPartToPortfolioCancel" OnCancelScript="cancelClickAddPartToPortfolio();"
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true" >
                    </asp:ModalPopupExtender>

Please note in the code posted above that the btnAddPart is included in an UpdatePanel. Here is how I am showing the popup:
aspx:
<asp:Button ID="btnAddPart" runat="server" Text="Add Part" style="height:23px;width:71px"
                       OnClientClick="ShowPopupAddPartToPortfolio(this); return true;"/>
javascript:
 var _popupAddPart;
        function ShowPopupAddPartToPortfolio(PopupBehaviorID)
        {
            this._popupAddPart = $find('ModalPopupAddPartToPortfolio');
            this._popupAddPart.show();            
        }

So the priblem was that the save button btnAddPartToPortfolioSave on the popup panel was not responding to the click at all (may be because the btnAddPart that initializes the popup is inside the updatePanel???). Therefore I had to force this button to postback. In the codebehind page load event I did the following:
btnAddPartToPortfolioSave.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}')", btnAddPartToPortfolioSave.UniqueID, "", "PortfolioPartsAdded");

and in the javascript:

function fnClickOK(sender, e, Flag)
       {
       switch(Flag)
            {
            case "Rename":
                var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                HiddenFlag.value=Flag;
                break;
            case "PortfolioPartsAdded":
                var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                HiddenFlag.value=Flag;
                //pageLoad(null, null);
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
            }  
       
          __doPostBack(sender,e);
       }

as you can see the aspx part of btnAddPartToPortfolioSave button, it has a server side click event defined:
<asp:Button ID="btnAddPartToPortfolioSave" runat="server" Text="Save" OnClick="btnAddPartToPortfolioSave_Click"/>

The server side click event has the following code and yes it does save the data extracted from a hidden variable to the database and tries to refresh the same page so that the popup is hidden and the data is refereshed in the page. See below:

protected void btnAddPartToPortfolioSave_Click(object sender, EventArgs e)
        {
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;// ReturnDDLSelectedItem();

            txtRenamePortfolioName.Text = PortfolioNm;

            dsPortfolios = (DataSet)Session["dsPortfolios"];
            DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            string PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            rdg.DeletePortfolioPartInfo("DeletePortfolioPartInfo", int.Parse(PortfolioID.ToString()));


            SavePopupPanelData("UpdatePortfolioPartInfo", int.Parse(PortfolioID.ToString()), "PortfolioParts");

           Session["dsPortfolios"] = null;
           Response.Redirect(string.Format("~/Portfolios.aspx?calledfrom={0}", "admin"));
                       
        }

However here comes the main issue. Every time the page loads, the ajax calls are run to fetch data to fill the two html select boxes that are part of the popup panels. When the ajax calls are made, the first one does not go to the http handler that fetches the data and the second one does. This is different behaviour from the initial page load when it correctly fetched data from both ajax calls. Here are the two ajax calls:

<script type="text/javascript">
   
     //Gets the browser specific XmlHttpRequest Object
        function getXmlHttpRequestObject()
        {      
            if (window.XMLHttpRequest)
            {            
                return new XMLHttpRequest(); //Not IE      
            }
            else if(window.ActiveXObject)
            {            
                return new ActiveXObject("Microsoft.XMLHTTP"); //IE      
            }
            else
            {            
                //Display your error message here and inform the user they might want to upgrade their browser.            
                alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade your browser.");      
            }
         }
         
         //Get our browser specific XmlHttpRequest object.
         var receiveReq = getXmlHttpRequestObject();
         //alert(receiveReq);
         var DataReturned;
         var AjaxSecondCallCompleted="False";
         
        function pageLoad(sender,args)
        {
                if(AjaxSecondCallCompleted=="True")
                    AjaxSecondCallCompleted="False"
                DataReturned="AllParts";
                getPortfolioParts();
           
        }
       
       
         function getPortfolioParts()
         {
            switch(DataReturned)
            {
            case "AllParts":
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                alert(CurrentPortfolio);
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio);
                alert(url);
                break;
            case "CurrentPortfolioParts":
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio) ;
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
            }  
           
           
             receiveReq.abort();
               
             receiveReq.open("GET", url, true);
             receiveReq.onreadystatechange = updatePage;
             receiveReq.send(null);
         }

       function updatePage()
       {
         if (receiveReq.readyState == 4)
         {
           if (receiveReq.status == 200)
           {alert(DataReturned);
            switch(DataReturned)
                {
                case "AllParts":
                    var elSel = document.getElementById('<% =lstAllParts.ClientID%>');
                    break;
                case "CurrentPortfolioParts":
                    var elSel = document.getElementById('<% =lstPortfolioParts.ClientID%>');
                    break;
                default:
                    //code to be executed if DataReturned is different from case 1 and 2
                }
               
                var response = receiveReq.responseText;
                alert(response);
                elSel.outerHTML = elSel.outerHTML.substring(0, elSel.outerHTML.indexOf('>', 0) + 1) + response + '</select>';
               
               
                if(AjaxSecondCallCompleted=="False")
                {
                    AjaxSecondCallCompleted="True"
                    DataReturned="CurrentPortfolioParts";
                    getPortfolioParts();                    
                }            
           }
          else
             alert("status is " + receiveReq.status);
         }
       }

It is complicated but may be as you said, the click event of the btnAddPartToPortfolioSave  may not be firing bacause the btnAddPart that initializes the popup is inside an Update Panel...Please let me know if you have any questions!
SOLUTION
Avatar of pradyahuja
pradyahuja
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Please see the whole code and explaination above. I am already forcing this button btnAddPartToPortfolioSave to postback. In the codebehind page load event I did the following:

btnAddPartToPortfolioSave.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}')", btnAddPartToPortfolioSave.UniqueID, "", "PortfolioPartsAdded");

and in the javascript:

function fnClickOK(sender, e, Flag)
       {
       switch(Flag)
            {
            case "Rename":
                var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                HiddenFlag.value=Flag;
                break;
            case "PortfolioPartsAdded":
                var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                HiddenFlag.value=Flag;
                //pageLoad(null, null);
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
            }  
       
          __doPostBack(sender,e);
       }

do you see any reason why the ajax calls are not properly running after the postback as they do before the postback?
seems like u  firing javascript PageLoad function from code behind.
can u paste that bit of code
I have attached the two aspx and cs files. Please remove the txt extension of the aspx file and review:
Portfolios.aspx.cs
Portfolios.aspx.txt
in any of those files,
I can not find calls to "pageLoad" js function
well if you see the pageLoad js function, it calls another function, see below:

function pageLoad(sender,args)
        {
            TriggerAjaxCall();
        }

The page load function is automatically called when the page loads(I am not calling it from code behind). However, I am calling the TriggerAjaxCall() function from the btnAddPartToPortfolioSave_Click event. See below:

protected void btnAddPartToPortfolioSave_Click(object sender, EventArgs e)
        {
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;// ReturnDDLSelectedItem();

            txtRenamePortfolioName.Text = PortfolioNm;

            dsPortfolios = (DataSet)Session["dsPortfolios"];
            DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            string PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            rdg.DeletePortfolioPartInfo("DeletePortfolioPartInfo", int.Parse(PortfolioID.ToString()));


            SavePopupPanelData("UpdatePortfolioPartInfo", int.Parse(PortfolioID.ToString()), "PortfolioParts");

            RetrieveData(true);

            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
            DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();

            string js=string.Empty;
            js = js + "TriggerAjaxCall()";
            jsMain = jsMain + js;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", jsMain, true);
                       
        }

Here is where the issue surfaces. When the pageLoad js function executes automatically when the page first loads, the two ajax calls are run as expected and fetch the data from the httphandler class I am attaching here. However, when the TriggerAjaxCall js function is called from the codebehind btnAddPartToPortfolioSave_Click event, it does not correctly fetch the data from the two ajax calls to httphandler class. Please see the attached:


AjaxDBConnectHandler.ashx.cs
try following


instead of


            string js=string.Empty;
            js = js + "TriggerAjaxCall()";
            jsMain = jsMain + js;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", jsMain, true);



make it

            string js=string.Empty;
            js = js + "TriggerAjaxCall()";

            Page.ClientScript.RegisterStartupScript(this.GetType(), "RefreshListAddItem", js, true);
I tried as you suggested but this does not help. When the TriggerAjaxCall js function is called from the codebehind btnAddPartToPortfolioSave_Click event, it does not correctly fetch the data from the two ajax calls to httphandler class and the two html select controls in the modal popup extender are still filled with the old data before adding/removing items between them. Is that something to do with restting the ajax XMLHttpRequest object?
definitely not.
is it possible that you can give me some dummy app with your code.
so that I can see it working myself.
well I would like to do that but that would be time consuming. I believe that I have provided enough info and code that should give you a good idea of what exactly I am trying to accomplish and what is the issue. What do you think?
ok...
let me try use your code in my test app..
will get back to...
honestly, your problem is interesting and I really want to solve it...
:)

and I am sure the issue is VERY SMALL
Here are most of the related tables script:

CREATE TABLE [dbo].[Accessories](
      [AccID] [int] IDENTITY(1,1) NOT NULL,
      [PLC] [bit] NULL,
      [AccPartNum] [varchar](25) NOT NULL,
      [SAPDesc] [char](40) NULL,
      [ProdRevID] [int] NULL,
      [PackageTypeID] [int] NULL,
      [AssocPartNum] [varchar](25) NULL,
      [MGroupsID] [int] NULL,
      [HSCID] [int] NULL,
      [HandheldID] [int] NULL,
      [UPC] [varchar](50) NULL,
      [OldEAN] [varchar](50) NULL,
      [EAN] [varchar](50) NULL,
      [JAN] [varchar](50) NULL,
      [LeadTime] [int] NULL,
      [TransitTime] [int] NULL,
      [MOI] [int] NULL,
      [LaunchVol] [int] NULL,
      [RawCost] [money] NULL,
      [LoadedCost] [money] NULL,
      [RIMTargCostMin] [money] NULL,
      [RIMTargCostMax] [money] NULL,
      [TargBulkPrice] [money] NULL,
      [ActBulkPrice] [money] NULL,
      [ReplacID] [int] NULL,
      [CommitID] [int] NULL,
      [MaterialStatusID] [int] NULL,
      [ECNStatusID] [int] NULL,
      [ChannelID] [int] NULL,
      [ProjectID] [int] NULL,
      [CRID] [int] NULL,
      [Scope] [varchar](50) NULL,
      [ScopeStatus] [varchar](10) NULL,
      [SecDesc] [varchar](1000) NULL,
      [Notes] [varchar](1000) NULL,
      [TargRelDate] [datetime] NULL,
      [TargFCSDate] [datetime] NULL,
      [RampStDate] [datetime] NULL,
      [KnownIssues] [varchar](100) NULL,
      [UMWeight] [varchar](15) NULL,
      [UnitWeight] [float] NULL,
      [UMDimension] [varchar](15) NULL,
      [OutsideUnitLength] [float] NULL,
      [OutsideUnitWidth] [float] NULL,
      [OutsideUnitHeight] [float] NULL,
      [CMReleased] [bit] NULL,
      [PrjMngPastScope] [bit] NULL,
      [PrjMngPresentScope] [bit] NULL,
      [BOMLevelID] [int] NULL,
      [WULevelID] [int] NULL,
 CONSTRAINT [PK_Accessories] PRIMARY KEY CLUSTERED
(
      [AccID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [UNIQUE_PartNumber] UNIQUE NONCLUSTERED
(
      [AccPartNum] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Primary key that uniquely identifies the table' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'AccID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'AccPartNum is a purchase level part number that partly identifies Accessories. We will keep the Purchase Level Part Numbers in the main Accessories table. In order to identify the PO Level Part Numbers that are associated with the top level PO Level Part numbers, we will add a field AssocPartNum and will populate this field with the related top level PO Level Part Number, if none exists, a zero value will be assigned to this column (self referencing). Source: Matrix.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'AccPartNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This is the 40 character part number that is stored in SAP. ACC stand for Accessories. ACC Description is the description of accessories used for the package. Description has to be pulled from SAP with limited 40 characters. All other descriptions (whether present in Peter’s spreadsheet or Frank’s spreadsheet) should be merged into Secondary Description field. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'SAPDesc'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'this field will store the related top level Purchase Level Part Number if any. Source: Matrix.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'AssocPartNum'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Foreign key referencing the parent table called MaterialGroups' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'MGroupsID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Foreign key referencing the parent table called HSCCodes' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'HSCID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Foreign key referencing the parent table called HHModels' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'HandheldID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'UPC is a 12 digits number and stands for Universal Product Code and is a unique serial number per commercial product that is used to identify the manufacturer and product name within the retail environment. UPCs are generally used in North America. The European equivalent is EAN (European Article Numbering system). Source: ABO.
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'UPC'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The European equivalent of UPC is EAN (European Article Numbering system). EAN is a 13 digits num with exact UPC num plus 1 extra digit. Source: ABO.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'EAN'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Amount of time it takes for the products to arrive from vendors from the time of order placement. Given in days. Source: SAP. Source: ABO.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'LeadTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This should be factured into the lead time' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'TransitTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Minimum Ordered Increment. MOI means that this is the minimum quantity to be ordered, but if you order more, then the system will reject it unless it is in multiples of the minimum order increment (MOI). E.g. if MOI=20, you can order 40, 60 etc. but not 21. Therefore the term MOQ previously used is misleading and is changed to MOI. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'MOI'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'The Marketing Channel team provides a launch volume based on the forecasting (Estimated xxk for the first 3 months). This quantity is then filled in the APBA (Advanced Purchase Buyer Authorization) form by the Product Management Group, have it approved by the director/VP and sent to the Commodity Management Group. The Commodity Management Group then execute on the APBA, send it to the supplier. Source: ABO.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'LaunchVol'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Vendor''s cost for the product before shipping. This is RIM’s internal cost and they do not want to make it available for the customer. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'RawCost'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'RIM’s overhead added into it, shipping included. This is RIM’s internal cost and they do not want to make it available for the customer. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'LoadedCost'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Target Raw Cost minimum range for product during design phase – not available to customer – meant for Program Management and Commodity team. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'RIMTargCostMin'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Target Raw Cost maximum range for product during design phase – not available to customer – meant for Program Management and Commodity team. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'RIMTargCostMax'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Target Starting price to customers for the product right after the release. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'TargBulkPrice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Actual Starting price to customers for the product once pricing is fully approved for release. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'ActBulkPrice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ReplacementID is the ID of PartNum that has replaced the current partNum. Source: SAP.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories', @level2type=N'COLUMN',@level2name=N'ReplacID'
GO
EXEC sys.sp_addextendedproperty @name=N'Source', @value=N'SAP/Matrix/ABO.' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Accessories'
GO
/****** Object:  Table [dbo].[PortFolios]    Script Date: 03/04/2010 06:49:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PortFolios](
      [PortFolioID] [int] IDENTITY(1,1) NOT NULL,
      [PortFolioNm] [varchar](50) NULL,
      [isPublic] [bit] NULL CONSTRAINT [DF_PortFolios_isPublic]  DEFAULT ((0)),
 CONSTRAINT [PK_PortFolios] PRIMARY KEY CLUSTERED
(
      [PortFolioID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_BOMLevels] FOREIGN KEY([BOMLevelID])
REFERENCES [dbo].[BOMLevels] ([BOMLevelID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_BOMLevels]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_Channels] FOREIGN KEY([ChannelID])
REFERENCES [dbo].[Channels] ([ChannelID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_Channels]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_Commitments] FOREIGN KEY([CommitID])
REFERENCES [dbo].[Commitments] ([CommitID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_Commitments]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_CRInfo] FOREIGN KEY([CRID])
REFERENCES [dbo].[CRInfo] ([CRID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_CRInfo]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_ECNStatusInfo] FOREIGN KEY([ECNStatusID])
REFERENCES [dbo].[ECNStatusInfo] ([ECNStatusID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_ECNStatusInfo]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_HHModels] FOREIGN KEY([HandheldID])
REFERENCES [dbo].[HHModels] ([HandheldID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_HHModels]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_HSCCodes] FOREIGN KEY([HSCID])
REFERENCES [dbo].[HSCCodes] ([HSCID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_HSCCodes]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_MaterialGroups] FOREIGN KEY([MGroupsID])
REFERENCES [dbo].[MaterialGroups] ([MGrpsID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_MaterialGroups]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_MaterialStatusInfo] FOREIGN KEY([MaterialStatusID])
REFERENCES [dbo].[MaterialStatusInfo] ([MaterialStatusID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_MaterialStatusInfo]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_PackageTypes] FOREIGN KEY([PackageTypeID])
REFERENCES [dbo].[PackageTypes] ([PackageTypeID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_PackageTypes]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_ProductRevisions] FOREIGN KEY([ProdRevID])
REFERENCES [dbo].[ProductRevisions] ([ProdRevID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_ProductRevisions]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_Projects] FOREIGN KEY([ProjectID])
REFERENCES [dbo].[Projects] ([ProjectID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_Projects]
GO
ALTER TABLE [dbo].[Accessories]  WITH CHECK ADD  CONSTRAINT [FK_Accessories_WULevels] FOREIGN KEY([WULevelID])
REFERENCES [dbo].[WULevels] ([WULevelID])
GO
ALTER TABLE [dbo].[Accessories] CHECK CONSTRAINT [FK_Accessories_WULevels]
the problem is your data fetching code.
is it possible to provide that as well?
and the related stored procs script:

USE [Accessories]
GO
/****** Object:  StoredProcedure [dbo].[UpdatePortfolioPartInfo]    Script Date: 03/04/2010 06:51:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[UpdatePortfolioPartInfo]
      @PortfolioID INT,
    @AccID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      
      INSERT INTO PortFolioAccLink VALUES (@PortfolioID, @AccID)

END


GO
/****** Object:  StoredProcedure [dbo].[DeletePortfolioPartInfo]    Script Date: 03/04/2010 06:51:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[DeletePortfolioPartInfo]
      @PortfolioID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;


      IF EXISTS (SELECT * FROM PortFolioAccLink WHERE PortFolioID=@PortfolioID)
            DELETE PortFolioAccLink WHERE PortFolioID=@PortfolioID

END


GO
/****** Object:  StoredProcedure [dbo].[ResetAllPartsAddedDltdUpdtdInfoForCurntUsr]    Script Date: 03/04/2010 06:51:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[ResetAllPartsAddedDltdUpdtdInfoForCurntUsr]
      @UserLogin VARCHAR(25)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      DECLARE @UserID INT

      SET @UserID=(SELECT UserID FROM Users WHERE Login=@UserLogin)

      UPDATE PortFolioUserLink
      SET PartsAddedDeletedUpdated=0
      WHERE UserID=@UserID      

END


GO
/****** Object:  StoredProcedure [dbo].[ResetPartsAddedDeletedUpdatedInfo]    Script Date: 03/04/2010 06:51:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ResetPartsAddedDeletedUpdatedInfo]
      @PortfolioID INT
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      UPDATE PortFolioUserLink
      SET PartsAddedDeletedUpdated=0
      WHERE PortfolioID=@PortfolioID      

END


GO
/****** Object:  StoredProcedure [dbo].[GetPartsAddedDeletedUpdatedInfo]    Script Date: 03/04/2010 06:51:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[GetPartsAddedDeletedUpdatedInfo]
      @PortfolioID INT
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      SELECT PartsAddedDeletedUpdated FROM PortFolioUserLink WHERE PortfolioID=@PortfolioID      

END


GO
/****** Object:  StoredProcedure [dbo].[GetAllAccParts]    Script Date: 03/04/2010 06:51:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[GetAllAccParts]
      
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;



SELECT DISTINCT AccID, AccPartNum, SAPDesc FROM Accessories
WHERE AccPartNum!='N/A'

--SELECT DISTINCT TOP 100 AccID, AccPartNum, SAPDesc FROM Accessories
--WHERE AccPartNum!='N/A'

END



GO
/****** Object:  StoredProcedure [dbo].[RenamePortfolioForCurrentUser]    Script Date: 03/04/2010 06:51:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[RenamePortfolioForCurrentUser]
@ToBeRenamedPortfolioID INT,
@RenamedPortfolioNM VARCHAR(25),
@UserLogin VARCHAR(25)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

DECLARE @UserID INT

SET @UserID=(SELECT UserID FROM Users WHERE Login=@UserLogin)

IF NOT EXISTS(SELECT * FROM Portfolios a
JOIN PortFolioUserLink b ON a.PortfolioID=b.PortfolioID
WHERE b.UserID=@UserID and a.PortfolioNM=@RenamedPortfolioNM)
      UPDATE a
      SET PortFolioNm=@RenamedPortfolioNM
      FROM Portfolios a JOIN PortFolioUserLink b ON a.PortfolioID=b.PortfolioID
      WHERE a.PortFolioID=@ToBeRenamedPortfolioID AND b.UserID=@UserID


END
GO
/****** Object:  StoredProcedure [dbo].[DeletePartFromPortfolio]    Script Date: 03/04/2010 06:51:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[DeletePartFromPortfolio]
      @AccID INT,
      @PortfolioID INT
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;


      IF EXISTS (SELECT * FROM PortFolioAccLink WHERE AccID=@AccID AND PortfolioID=@PortfolioID)
            BEGIN
                  DELETE PortFolioAccLink WHERE AccID=@AccID AND PortfolioID=@PortfolioID

                  --Change the PartsAddedDeletedUpdated to true for the portfolio changed
                  --This will allow the front app to decide whether reload the data from the db or not
                  --if the flag is true then data should be reloaded, otherwise not
                  UPDATE PortFolioUserLink
                  SET PartsAddedDeletedUpdated=1
                  WHERE PortfolioID=@PortfolioID
            END

END


GO
/****** Object:  StoredProcedure [dbo].[GetPortfolioByPortfolioID]    Script Date: 03/04/2010 06:51:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[GetPortfolioByPortfolioID]
    @PortfolioID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      
      
      SELECT * FROM Portfolios
      WHERE PortfolioID=@PortfolioID

END


GO
/****** Object:  StoredProcedure [dbo].[GetSelectedPublicPortfolioInfo]    Script Date: 03/04/2010 06:51:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetSelectedPublicPortfolioInfo] --40
@PortfolioID INT
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

SELECT PortfolioNm, c.PortfolioID, isPublic, a.[Login] FROM
Users a  JOIN PortFolioUserLink b ON a.UserID=b.UserID
JOIN Portfolios c ON b.PortfolioID=c.PortfolioID
WHERE b.PortfolioID=@PortfolioID


END
GO
/****** Object:  StoredProcedure [dbo].[UpdatePrivacyFlagForSelectedPortfolio]    Script Date: 03/04/2010 06:51:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[UpdatePrivacyFlagForSelectedPortfolio]
@PortfolioID INT,
@isPublic bit
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      UPDATE Portfolios
      SET isPublic=@isPublic
      WHERE PortFolioID=@PortfolioID


END
GO
/****** Object:  StoredProcedure [dbo].[GetPartsForCurrentPortfolio]    Script Date: 03/04/2010 06:51:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[GetPartsForCurrentPortfolio] --21
    @PortfolioID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      TRUNCATE TABLE PartsForCurrentPortfolio

      INSERT INTO PartsForCurrentPortfolio
      SELECT b.AccID, b.AccPartNum , b.SAPDesc, NULL AS Inbox, e.ClanNm AS [MG L3] FROM PortFolioAccLink a
      JOIN Accessories b ON a.AccID=b.AccID JOIN MaterialGroups c ON b.MGroupsID=c.MGrpsID
      JOIN Families d ON c.FamilyID=d.FamilyID JOIN Clans e ON d.ClanID=e.ClanID
      WHERE PortFolioID=@PortfolioID

      SELECT * FROM PartsForCurrentPortfolio

END


GO
/****** Object:  StoredProcedure [dbo].[UpdatePortfolioUserInfo]    Script Date: 03/04/2010 06:51:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[UpdatePortfolioUserInfo]
      @UserLogin VARCHAR(25),
    @PortfolioID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      DECLARE @UserID INT

      SET @UserID=(SELECT UserID FROM Users WHERE [Login]=@UserLogin)
      
      INSERT INTO PortfolioUserLink(PortFolioID, UserID) VALUES (@PortFolioID, @UserID)

END


GO
/****** Object:  StoredProcedure [dbo].[UpdatePortfolioInfo]    Script Date: 03/04/2010 06:51:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[UpdatePortfolioInfo]
      @AccID INT,
    @PortfolioID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      
      INSERT INTO PortfolioAccLink VALUES (@PortFolioID, @AccID)

END


GO
/****** Object:  StoredProcedure [dbo].[AddNewPortfolio]    Script Date: 03/04/2010 06:51:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[AddNewPortfolio]
    @PortfolioNm VARCHAR(50),
      @Identity int OUT
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.

      INSERT INTO Portfolios (PortFolioNm) VALUES(@PortfolioNm)

      SET @Identity = SCOPE_IDENTITY()



END


GO
/****** Object:  StoredProcedure [dbo].[GetPartsForGivenHandheld]    Script Date: 03/04/2010 06:51:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetPartsForGivenHandheld] --53
    @HandheldID INT

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
      DECLARE @HandheldNm VARCHAR(50)
      DECLARE @QueryString VARCHAR(350)
      SET @HandheldNm=(SELECT HHMktNM FROM HHModels WHERE HandheldID=@HandheldID)

      TRUNCATE TABLE PartsForCurrentPortfolio

      SET @QueryString='INSERT INTO PartsForCurrentPortfolio '
      SET @QueryString=@QueryString + 'SELECT b.AccID, a.AccPartNum , b.SAPDesc, NULL AS Inbox, e.ClanNm AS [MG L3]' --+ ' FROM CompatibilityMatrixSrc WHERE '
      SET @QueryString=@QueryString + ' FROM CompatibilityMatrixSrc a JOIN Accessories b ON a.AccPartNum=b.AccPartNum JOIN MaterialGroups c ON b.MGroupsID=c.MGrpsID JOIN Families d ON c.FamilyID=d.FamilyID JOIN Clans e ON d.ClanID=e.ClanID WHERE '
      SET @QueryString=@QueryString + '[' + @HandheldNm + ']'
      SET @QueryString=@QueryString + '= 1'


      --select @QueryString

      EXEC(@QueryString)
      
      SELECT * FROM PartsForCurrentPortfolio

END


GO
/****** Object:  StoredProcedure [dbo].[GetAllPortfoliosForCurrentUser]    Script Date: 03/04/2010 06:51:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetAllPortfoliosForCurrentUser] --'SKALEEM|BAT-06532-001'
@UserLoginAndPartNum VARCHAR(50)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

DECLARE @Pos INT, @UserLogin VARCHAR(25), @PartNumber VARCHAR(25)
            SET @Pos=CHARINDEX('|', @UserLoginAndPartNum)
            SET @UserLogin=SUBSTRING(@UserLoginAndPartNum, 1, @Pos-1)
            SET @PartNumber=SUBSTRING(@UserLoginAndPartNum, @Pos+1, LEN(@UserLoginAndPartNum) )
--SELECT @Pos AS POS
--PRINT @InputParamPart
--PRINT @UserLoginAndPartNum
--PRINT @UserLogin
--PRINT @PartNumber
DECLARE @UserID INT

SET @UserID=(SELECT UserID FROM Users WHERE Login=@UserLogin)

SELECT PortfolioNm, a.PortfolioID, isPublic, [Login] FROM PortfolioUserLink a
JOIN Portfolios b ON a.PortfolioID=b.PortfolioID
JOIN Users c ON a.UserID=c.UserID
WHERE a.UserID=@UserID OR isPublic=1
ORDER BY isPublic

SELECT AccID, AccPartNum, SAPDesc, SecDesc FROM Accessories
WHERE AccPartNum = @PartNumber

----Compatibility
----First call the GenerateCompatibilityMatrix stored proc to process and refresh the compatibility report
--EXEC GenerateCompatibilityMatrix

SELECT * FROM AccCompatibilitySrc
WHERE AccPartNum=@PartNumber


END
GO
/****** Object:  StoredProcedure [dbo].[GetCurrentPortfolioForCurrentUser]    Script Date: 03/04/2010 06:51:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetCurrentPortfolioForCurrentUser]
@UserLogin VARCHAR(25)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

DECLARE @UserID INT

SET @UserID=(SELECT UserID FROM Users WHERE Login=@UserLogin)

SELECT PortfolioNm, b.PortfolioID, isPublic, [Login] FROM
Users a JOIN UserCurrentPortfolioLink b ON a.UserID=b.UserID
JOIN Portfolios c ON b.PortfolioID=c.PortfolioID
WHERE b.UserID=@UserID


END
GO
/****** Object:  StoredProcedure [dbo].[SaveCurrentPortfolioForCurrentUser]    Script Date: 03/04/2010 06:51:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SaveCurrentPortfolioForCurrentUser]
@Portfolio VARCHAR(25),
@UserLogin VARCHAR(25)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

DECLARE @UserID INT
DECLARE @PortfolioID INT

SET @UserID=(SELECT UserID FROM Users WHERE Login=@UserLogin)
SET @PortfolioID=(SELECT a.PortfolioID FROM Portfolios a JOIN PortfolioUserLink b ON a.PortfolioID=b.PortfolioID WHERE PortFolioNm=@Portfolio AND UserID=@UserID)

IF EXISTS(SELECT * FROM UserCurrentPortfolioLink WHERE UserID=@UserID)
      UPDATE UserCurrentPortfolioLink
      SET PortfolioID=@PortfolioID
      WHERE UserID=@UserID
ELSE
      INSERT INTO UserCurrentPortfolioLink(UserID, PortfolioID) VALUES (@UserID, @PortfolioID)


END
Also this table script:

CREATE TABLE [dbo].[Users](
      [UserID] [int] IDENTITY(1,1) NOT NULL,
      [Login] [varchar](25) NULL,
      [UserNm] [varchar](50) NULL,
      [UserPhone] [varchar](20) NULL,
      [UserAddress] [varchar](70) NULL,
      [UserEmail] [varchar](50) NULL,
      [Internal] [bit] NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
      [UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial