ASP.NET custom control: when is LoadPostData() called?

我们两清 提交于 2019-12-05 04:48:38

I am a little late jumping in on this but, just for future reference, here is how I accomplished something similar…

My control is a tree that uses templates for the nodes. The issue where I was dealing with this was how to capture the client side changes to the expanded/collapsed state of the nodes. What ended up working was:

In CreateChildControls add the hidden field to the controls collection of my root control.

protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
    ...
    _cdExpanded = new HiddenField();
    _cdExpanded.ID = "cdExpanded";
    this.Controls.Add(_cdExpanded);
    ...
}

In OnInit call

protected override void OnInit(EventArgs e)
{
    ...
    Page.RegisterRequiresPostBack(this);
    ...
}

In LoadPostData look for a value in the post collection that matches the UniqueID (not ClientID) of the hidden field:

public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
    ...
    string cdExpanded = postCollection[_cdExpanded.UniqueID];
    ...
}

Within the classes for the individual nodes I have code which populates the onclick events of my toggle buttons with a call to a JavaScript function which takes the ID of the base control and the individual nodes as arguments.

    string ToggleScript
    {
        get
        {
            return "ToggleNode('" + this.ClientID + "', '" + _TreeRoot.ClientID + "');";
        }
    }
    protected override void Render(HtmlTextWriter writer)
    {
        ...
        if (this.HasChildren)
        {
            writer.AddAttribute("onclick", ToggleScript);
        }
        ...
    }

This makes it so that finding the hidden field is fairly easy via getElementById:

function ToggleNode(nodeID, treeID) {
var cdExpanded = document.getElementById(treeID + "_cdExpanded");
...
}

The JavaScript then modifies the value of the hidden field as needed for the event that occurred. When we get back to the server I am able to parse out the contents of this field and modify the control state as necessary before it gets rendered again. (Note: I actually use 3 hidden fields for tracking different events but the concept is the same)

Hope this helps others in the future…

Sounds really odd to be working only when an item is selected. A quick way to check if LoadPostData is being invoked would to enable tracing and put the following in IPostBackDataHandler.LoadPostData(...).

Page.Trace.Write("My control", "LoadPostData");

If that is the case, you should make sure that you've got the following:

Page.RegisterRequiresPostBack(this) in OnInit

Here is a full sample control.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Design;
using System.ComponentModel;
using System.Web.UI.Design;

namespace Controls
{
    public sealed class ExtendedListBoxDesigner : ControlDesigner
    {

        public override string GetDesignTimeHtml()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<div>My designer</div>");
            return sb.ToString();
        }

    }

    [DesignerAttribute(typeof(ExtendedListBoxDesigner), typeof(IDesigner))]
    public class ExtendedListBox : ListBox, INamingContainer, IPostBackDataHandler 
    {
        bool IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            Page.Trace.Write("ExtendedListBox", "LoadPostData");
            return true;
        }


        protected override void OnInit(EventArgs e)
        {
            Page.RegisterRequiresPostBack(this);
            base.OnInit(e);
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
            writer.Write(string.Format("<input type=\"hidden\" name=\"{0}_dummy\" value=\"alwaysPostBack\">", this.ID));
        }

    }
}

and the page looks like this.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ControlSamlpe._Default" Trace="true" %>
<%@ Register Assembly="Controls" Namespace="Controls" TagPrefix="sample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <sample:ExtendedListBox runat="server" ID="extListBox"></sample:ExtendedListBox>
    <asp:Button runat="server" ID="go" />
    </div>
    </form>
</body>
</html>

When you click on go, you should see "LoadPostData" in the trace.

I've established that the LoadPostData() method is not called unless the post data contains an item with the same name as the control's UniqueID. [Edit: calling Page.RegisterRequiresPostback during Init() overcomes this.] I can see why, but it is quite limiting.

I have overcome the problem by not handling it during the LoadPostData() method at all. Instead, I have handled it in a method which I call in OnLoad() instead.

Two things need to be borne in mind when using this approach:

1) You no longer have access to the postCollection NameValueCollection object which is passed in to the LoadPostData() method as an argument. This means you have to extract the post data from the Request.Form collection, which is slightly harder work. 2) Since OnLoad() occurs after the ViewState processing code, you will need to manually set the SelectedValue after you create the ListItems. If you don't, if the listbox is populated via AJAX and the user makes a selection, the selection will be lost.

I hope this helps someone in the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!