为扩展控件添加服务器端事件

5
我有一个扩展控件,它在用户完成输入500毫秒后触发文本框的OnTextChanged事件。问题在于,由于回发的原因,当文本框失去焦点时会触发OnTextChanged,从而导致问题。
我想做的是给扩展控件添加自己的服务器端事件(比如OnDelayedSubmit),以便我可以单独处理它。该事件将起源于扩展控件的行为脚本(经过500毫秒延迟),因此在onchanged中放置__doPostBack不是一个选择。
有人能够解释一下如何实现这个吗?
1个回答

5

在深入研究了扩展控件和JavaScript之后,我拼凑出了一个看起来目前运行良好的解决方案。

主要的技巧是将必要的PostBack代码从服务器端传递到客户端行为脚本。我通过使用ExtenderControlProperty(在控件的OnPreRender函数中设置),然后在行为脚本中进行评估来实现这一点。其余部分是基本的事件处理。

因此,现在我的扩展控件的.cs文件大致如下:

public class DelayedSubmitExtender : ExtenderControlBase, IPostBackEventHandler
{
    // This is where we'll give the behavior script the necessary code for the 
    // postback event
    protected override void OnPreRender(EventArgs e)
    {
        string postback = Page.ClientScript.GetPostBackEventReference(this, "DelayedSubmit") + ";";
        PostBackEvent = postback;
    }

    // This property matches up with a pair of get & set functions in the behavior script
    [ExtenderControlProperty]
    public string PostBackEvent
    {
        get
        {
            return GetPropertyValue<string>("PostBackEvent", "");
        }
        set
        {
            SetPropertyValue<string>("PostBackEvent", value);
        }
    }

    // The event handling stuff
    public event EventHandler Submit;  // Our event

    protected void OnSubmit(EventArgs e)  // Called to raise the event
    {
        if (Submit != null)
        {
            Submit(this, e);
        }
    }

    public void RaisePostBackEvent(string eventArgument)  // From IPostBackEventHandler
    {
        if (eventArgument == "DelayedSubmit")
        {
            OnSubmit(new EventArgs());
        }
    }

}

我的行为脚本大致如下:

DelayedSubmitBehavior = function(element) {
    DelayedSubmitBehavior.initializeBase(this, [element]);

    this._postBackEvent = null; // Stores the script required for the postback
}

DelayedSubmitBehavior.prototype = {
    // Delayed submit code removed for brevity, but normally this would be where 
    // initialize, dispose, and client-side event handlers would go

    // This is the client-side part of the PostBackEvent property
    get_PostBackEvent: function() {
        return this._postBackEvent;
    },
    set_PostBackEvent: function(value) {
        this._postBackEvent = value;
    }

    // This is the client-side event handler where the postback is initiated from
    _onTimerTick: function(sender, eventArgs) {
        // The following line evaluates the string var as javascript,
        // which will cause the desired postback
        eval(this._postBackEvent);
    }
}

现在,服务器端的事件可以像处理其他控件上的事件一样进行处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接