从 ASP.NET 自定义 Web 控件检索输入值

问题描述 投票:0回答:2

我正在构建一个 Web 控件来模糊 SSN 等输入值。

我已经编写了控件,但是,我无法在回发时检索输入值。

[DefaultProperty("Text")]
[ToolboxData("<{0}:Mask runat=server></{0}:Mask>")]
public class Mask: WebControl, INamingContainer {

    const string INPUT_PREFIX = "_input";

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    public string Text {
        get {
            return text;
        }
        set {
            text = value;
        }
    }

    protected override void RenderContents(HtmlTextWriter output) {
        output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
        
        output.RenderBeginTag(HtmlTextWriterTag.Div);

        output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
        output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID + INPUT_PREFIX);
        output.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);

     
        output.RenderBeginTag(HtmlTextWriterTag.Input);
        output.RenderEndTag();

        output.RenderEndTag();
    }

    protected override void Render(HtmlTextWriter writer) {
        this.RenderContents(writer);
    }
}

我想我一切都是对的。我尝试过实现 ipostbackdatahandler 但也不起作用。

有人可以帮我吗?

谢谢

c# asp.net user-controls custom-controls
2个回答
0
投票

尝试改变

    public string Text
    {
        get
        {
            return text;
        }
        set
        {
            text = value;
        }
    }

至:

   public string Text
   {
      get
      {
         string text = (string)ViewState["Text"];
         return text ?? string.Empty;
      }
      set
      {
         ViewState["Text"] = value;
      }
  }

0
投票

我能够检索以下值:

 public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) {
        text = postCollection[postDataKey + INPUT_PREFIX];
        return false;
    }

并将控件注册为需要回发

 protected override void OnInit(EventArgs e) {
        Page.RegisterRequiresPostBack(this);
    }
© www.soinside.com 2019 - 2024. All rights reserved.