简体   繁体   English

最好的方法来执行用户控制代码?

[英]Best way to do user control code behind?

I have this very simple control below. 我在下面有这个非常简单的控制。 And on the page that i use this control I'd just like to be able to say: ucMessagePanel.SetMessage(...) , but it does not allow me to declare a static method. 在我使用此控件的页面上,我只想说: ucMessagePanel.SetMessage(...) ,但它不允许我声明静态方法。 I tried doing it with Static properties and that works just fine, but shouldn't I also be able to use static methods? 我尝试使用静态属性,并且工作正常,但我不应该也能使用静态方法?

    <center>
    <asp:Panel ID="pnlMessage" runat="server" >
        <asp:Label ID="lblMessage" runat="server" />
    </asp:Panel>
</center>


public partial class ucMessagePanel : System.Web.UI.UserControl
{        
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public static void SetMessage(string message, string mssgCssClass)
    {
        lblMessage.Text = message;
        pnlMessage.CssClass = mssgCssClass;
    }
}

You don't need static methods. 您不需要静态方法。 When you declare the user control in the ASPX page, you can reference it directly by the ID. 在ASPX页面中声明用户控件时,可以直接通过ID引用它。

In the ASPX: 在ASPX中:

<uc:SomeUserControl ID="UserControl1" runat="server" ...>

And in the code behind: 并在代码背后:

UserControl1.SetMessage("Some message");

In the user control, change the method to something like this: 在用户控件中,将方法更改为以下内容:

public void SetMessage(string Message)
{
    lblMessage.Text = Message;
}

Static methods can't access items contained on an instance of the control. 静态方法无法访问控件实例中包含的项。 For example; 例如; if you had two concurrent requests running; 如果你有两个并发请求在运行; and you call the static method; 你调用静态方法; which instance of the ucMessagePanel class would it modify (this even bypassing the issue of the code provided couldn't compile)? 它将修改ucMessagePanel类的哪个实例(这甚至绕过了提供的代码无法编译的问题)?

There is no way you should have been able to edit those controls with a static property either, unless you were taking the value of the static property and assigning it to the control using an instance method. 除非您使用静态属性的值并使用实例方法将其分配给控件,否则您无法使用静态属性编辑这些控件。

You should avoid using static in ASP.NET request processing unless it is something you need to share between request threads. 您应该避免在ASP.NET请求处理中使用static ,除非您需要在请求线程之间共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM