Async/partial postback datagrid issues

2019-08-02 13:52发布

问题:

I'm trying to get an aspx datagrid control to perform a post that results in a partial postback (asynchronous) rather than a full postback. I've added scriptmanager, an update panel, and a content template wrapper and yet it still refreshes the page when i select a data item and click add.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" ></asp:ScriptManager>
 <asp:UpdatePanel ID="upPnlLookup" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
        <ContentTemplate>
            <asp:DataGrid ID="ObjectPropertiesDataGrid" CellPadding="5" CellSpacing="5" OnItemCommand="ObjectPropertiesDataGrid_ItemCommand" OnItemDataBound="ObjectPropertiesDataGrid_ItemDataBound" AutoGenerateColumns="False" CssClass="List" DataKeyField="id" runat="server">
              <asp:TemplateColumn>
               <ItemTemplate>
                 <asp:Panel ID="multiValuePanel" Visible="false" runat="server">
                        <table>
                           <tr>
                             <td valign="top">
                                 <asp:Button ID="addButton" CssClass="button" CommandName="AddValue" Width="65px" Text="Add" runat="server"></asp:Button>
                                 <asp:Button ID="addAllButton" CssClass="button" CommandName="AddAllValue" Width="85px" Text="Add All" runat="server"></asp:Button>
                                 <br />
                                <asp:ListBox ID="listBoxValues" Width="250px" CssClass="listbox" SelectionMode="Multiple"  runat="server"></asp:ListBox>
                              </td>
                              <td valign="top">
                                <asp:Button ID="removeButton" CssClass="button" Text="Remove" Width="65px" CommandName="RemoveValue"   runat="server"></asp:Button>
                                <asp:Button ID="removeAllButton" CssClass="button" Text="Remove All" Width="85px" CommandName="RemoveAllValue" runat="server"></asp:Button>
                                  <br />
                               <asp:ListBox ID="listBoxCurrentValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
                              </td>                                         
                             </tr>
                       </table>
               </asp:Panel>
        </ItemTemplate>
  </asp:TemplateColumn>
</asp:DataGrid>
</ContentTemplate>
     <Triggers>
         <asp:AsyncPostBackTrigger ControlID="addButton" EventName="Click" />
         <asp:AsyncPostBackTrigger ControlID="removeButton" EventName="Click" />
         <asp:AsyncPostBackTrigger ControlID="addAllButton" EventName="Click" />
         <asp:AsyncPostBackTrigger ControlID="removeAllButton" EventName="Click" />
     </Triggers>
</asp:UpdatePanel>

Code Behind (snippets/relevant methods):

 protected void Page_Load(object sender, EventArgs e)
    {
        SaveButton.Click += SaveButton_Click;
        btnAddChild.Click += btnAddChild_Click;
        btnAddChildTop.Click += btnAddChildTop_Click;
        DeleteButton.Click += DeleteButton_Click;
        CancelButton.Click += CancelButton_Click;
        CopyButton.Click += CopyButton_Click;
        NewButton.Click += NewButton_Click;
        AddSiteButton.Click += AddSiteButton_Click;
        RemoveSiteButton.Click += RemoveSiteButton_Click;
        ActivateAll.Click += ActivateAll_Click;
        DeactivateAll.Click += DeactivateAll_Click;
        startDateCalender.SelectionChanged += startDateCalender_SelectionChanged;
        endDateCalender.SelectionChanged += endDateCalender_SelectionChanged;
        startDateCalender.Load += startDateCalender_Load;
        endDateCalender.Load += endDateCalender_Load;
        CacheButton.Click += CacheButton_Click;


        if (IsPostBack)
            return;
        if (String.IsNullOrEmpty(Request["id"]))
        {
            Response.Redirect("default.aspx");
        }
        else
        {
            LoadData();
        }
    }

    private void LoadData()
    {
        Properties = ContentProviderFactory.GetContentProvider().GetObjectTypeProperties(CurrentContentObject.Type, false);
        uploadImage.DataSource = DataHelper.GetObjecTypeImageSizes(CurrentContentObject.Type);
        uploadImage.Container = CurrentContentObject;


        foreach (var property in from Property p in Properties
                               let objectProperty = CurrentContentObject.GetProperty(p.Id)
                               where objectProperty == null
                               select p)
        {
            CurrentContentObject.Items.Add(property);
        }

        ObjectPropertiesDataGrid.DataSource = Properties;
        var children = ContentProviderFactory.GetContentProvider().GetContentObjectChildren(CurrentContentObject.Id);

        dgObjectChildren.DataSource = children.Where(c => c.Active);
        dgObjectInactiveChildren.DataSource = children.Where(c => !c.Active);

        dgObjectParents.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectParents(CurrentContentObject);
        ddlContentTypes.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
        ddlContentTypesTop.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);

        SitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSitesAvailable(CurrentContentObject.Id);
        SetSitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSites(CurrentContentObject.Id);

        if (CurrentContentObject.Id == 0)
        {
            Response.Status = "301 Moved Permanently";
            Response.AddHeader("Location", "/admin/Contentobjects/ObjectNotFound.aspx");
            Response.End();
        }

        const string DATE_FORMAT = "MM/dd/yyyy";

        if (CurrentContentObject.StartDate.ToString(DATE_FORMAT) != SqlDateTime.MinValue.Value.ToString(DATE_FORMAT))
        {
            startDateTextBox.Text = CurrentContentObject.StartDate.ToShortDateString();
        }
        if (CurrentContentObject.EndDate.ToString(DATE_FORMAT) != SqlDateTime.MaxValue.Value.ToString(DATE_FORMAT))
        {
            endDateTextBox.Text = CurrentContentObject.EndDate.Date.ToShortDateString();
        }

        DataBind();

        //if its an orphan child/child, remove 'add child' button and pulldown
        if (ddlContentTypes.Items.Count == 0)
        {
            btnAddChild.Visible = false;
            ddlContentTypes.Visible = false;
        }
        if (ddlContentTypesTop.Items.Count == 0)
        {
            ddlContentTypesTop.Visible = false;
            btnAddChildTop.Visible = false;
        }

        // Add delete confirmation javascript
        DeleteButton.Attributes["onclick"] = "return confirm_object_delete();";

        RenderTypeHeader();
        RenderBreadcrumb();

        if (CurrentContentObject.ParentId == 0)
        {
            UserInfo.AddToHistory(CurrentContentObject.Id, CurrentContentObject.Name);
        }
        else
        {
            UserInfo.AddToHistory(CurrentContentObject.Parent.Id, CurrentContentObject.Parent.Name);
        }

        startCalenderPanel.Visible = false;
        endCalenderPanel.Visible = false;
    }


        protected void ObjectPropertiesDataGrid_ItemCommand(object sender, DataGridCommandEventArgs e)
    {
        var id = (int)ObjectPropertiesDataGrid.DataKeys[e.Item.ItemIndex];

        switch (e.CommandName.ToLower())
        {
            case "clearimage":
                {
                    // Delete the image (does not physically remove the image but will be replaced if new a new one updates)
                    var imageProperty = e.Item.FindControl("imageProperty") as Image;
                    var tbFileName = e.Item.FindControl("tbFileName") as TextBox;

                    tbFileName.Text = string.Empty;
                    imageProperty.ImageUrl = string.Empty;

                    break;
                }
            case "addvalue":
                {
                    // Adds a property value to the list of properites
                    var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
                    var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;

                    foreach(var item in listBoxValues.Items.Cast<ListItem>().Where(item => item.Selected))
                    {
                        // Add item to the set values
                        listBoxCurrentValues.Items.Add(item);
                    }

                    for (var i = listBoxValues.Items.Count - 1; i >= 0; i--)
                    {
                        if (listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
                        {
                            listBoxValues.Items.RemoveAt(i);
                        }
                    }

                    SortListBox(listBoxCurrentValues);
                    break;
                }
            case "removevalue":
                {
                    var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
                    var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;

                    for(var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
                    {
                        if(listBoxCurrentValues.Items[i].Selected)
                        {
                            listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
                            listBoxCurrentValues.Items.RemoveAt(i);
                        }
                    }

                    SortListBox(listBoxValues);
                    break;
                }
            case "addallvalue":
                {
                    var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
                    var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;

                    foreach(ListItem item in listBoxValues.Items)
                    {
                        // Add item to the set values
                        listBoxCurrentValues.Items.Add(item);
                    }

                    for(var i = listBoxValues.Items.Count - 1; i >= 0; i--)
                    {
                        if(listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
                        {
                            listBoxValues.Items.RemoveAt(i);
                        }
                    }

                    SortListBox(listBoxCurrentValues);

                    break;
                }
            case "removeallvalue":
                {
                    var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
                    var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;

                    for (var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
                    {
                        listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
                        listBoxCurrentValues.Items.RemoveAt(i);
                    }

                    SortListBox(listBoxValues);

                    break;
                }
            case "addalldatalistvalue":
                {
                    var dataListValues = e.Item.FindControl("DataListValues") as DataList;
                    var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;

                    foreach (DataListItem item in dataListValues.Items)
                    {
                        ImageLink imageLink = ImageLinks[id][item.ItemIndex];
                        CurrentImageLinks[id].Add(imageLink);
                    }

                    for (var i = dataListValues.Items.Count - 1; i >= 0; i--)
                    {
                        if (CurrentImageLinks[id].Contains(ImageLinks[id][i]))
                        {
                            ImageLinks[id].RemoveAt(i);
                        }
                    }

                    dataListValues.DataSource = ImageLinks[id];
                    dataListCurrentValues.DataSource = CurrentImageLinks[id];
                    dataListValues.DataBind();
                    dataListCurrentValues.DataBind();
                    break;
                }
            case "removealldatalistvalue":
                {
                    var dataListValues = e.Item.FindControl("DataListValues") as DataList;
                    var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;

                    for (var i = dataListCurrentValues.Items.Count - 1; i >= 0; i--)
                    {
                        ImageLinks[id].Add(CurrentImageLinks[id][i]);
                        CurrentImageLinks[id].RemoveAt(i);
                    }

                    dataListValues.DataSource = ImageLinks[id];
                    dataListCurrentValues.DataSource = CurrentImageLinks[id];
                    dataListValues.DataBind();
                    dataListCurrentValues.DataBind();

                    break;
                }
        }
    }

回答1:

I think you have a runtime error in Page_Load. for example if you have this wrong codes, your page will refresh instead of update:

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            Response.Redirect("WebForm1.aspx");
            int.Parse("");

        }
    }


回答2:

also try this :

Control me = FindControl(Request.Params.Get("__EVENTTARGET"));
if(FindControl(me!=addButton && me!=removeButton && me!=addAllButton && me!=removeAllButton)
 {
    if (IsPostBack)
        return;
    if (String.IsNullOrEmpty(Request["id"]))
    {
        Response.Redirect("default.aspx");
    }
    else
    {
        LoadData();
    }
 }