在asp.net中可重复使用的Page_ preRender功能 [英] Reusable Page_PreRender function in asp.net

查看:427
本文介绍了在asp.net中可重复使用的Page_ preRender功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这台我的LinkBut​​ton作为面板的默认按钮的功能。

I have a function which sets my linkbutton as the default button for a panel.

protected void Page_PreRender(object sender, EventArgs e)
    {
        string addClickFunctionScript = @"function addClickFunction(id) {
               var b = document.getElementById(id);
               if (b && typeof(b.click) == 'undefined')
                 b.click = function() {
                   var result = true;
                   if (b.onclick) result = b.onclick();
                   if (typeof(result) == 'undefined' || result)
                     eval(b.getAttribute('href'));
                 }
             };";

        string clickScript = String.Format("addClickFunction('{0}');", lbHello.ClientID);

        Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + lbHello.ClientID, clickScript, true);
    }

这工作正常。如何使这个可重用我我的应用程序的所有页面。一个页面可以有多个linkbuttons和多个面板....任何建议...

This works fine. How to make this reusable to all my pages of my application. One page can have multiple linkbuttons and multiple panels.... Any suggestion...

推荐答案

最彻底的方法是使用从的LinkBut​​ton 继承的自定义服务器控件。实际上这似乎是在与<线href=\"http://kpumuk.info/asp-net/using-panel-defaultbutton-property-with-linkbutton-control-in-asp-net/\"相对=nofollow>从<一个博客帖子 href=\"http://stackoverflow.com/questions/3581369/set-linkbutton-as-default-button-for-asppanel-in-asp-net\">earlier问题。所有你需要做的是覆盖在preRender 事件并粘贴code你必须同时改变 lbHello.ClientID this.ClientID 来指代控制的具体实例。它不应该超过10分钟,设置起来。一旦做到这一点,您可以根据需要在一个页面上使用尽可能多的控件,轻松地支持整个应用程序的各个页面。

The cleanest way would be to use a custom server control that inherits from LinkButton. In fact this seems to be in line with the blog post from your earlier question. All you need to do is override the OnPreRender event and paste the code you have while changing lbHello.ClientID to this.ClientID to refer to the specific instance of that control. It should not take more than 10 minutes to set this up. Once this is done, you can use as many of the controls as you want on one page and easily support it throughout your application's various pages.

遵循以下我的指示时,明确了创建服务器控件一节中,您可能会发现这个MSDN文章有所帮助:的演练:开发和使用自定义Web服务器控件。这里有一个一步一步的指导,以实现这一点:

You might find this MSDN article helpful when following my instructions below, specifically the "Creating the Server Control" section: Walkthrough: Developing and Using a Custom Web Server Control. Here's a step by step guide to accomplishing this:


  1. 在现有解决方案中添加一个新的ASP.NET服务器控件项目(右键单击在解决方案资源管理解决方案 - >添加新项目 - > ASP.NET服务器控件)。将它命名为 LinkBut​​tonDefault (你可以自由地改名字,当然)。

  2. 重命名 ServerControl1.cs LinkBut​​tonDefault.cs

  3. 文件中的名称空间重命名为 CustomControls

  4. 执行步骤12-14 MSDN文章中通过打开的AssemblyInfo.cs 文件(包含在属性该项目的文件夹)。在文件的底部添加此行: [汇编:标签preFIX(CustomControls,CC)]

  5. LinkBut​​tonDefault.cs 添加此code重写在preRender 事件:

  1. In your existing solution add a new ASP.NET Server Control project (right click on your solution from the Solution Explorer -> Add New Project -> ASP.NET Server Control). Name it LinkButtonDefault (you're free to change the name, of course).
  2. Rename ServerControl1.cs to LinkButtonDefault.cs
  3. Rename the namespace in the file to CustomControls
  4. Perform steps 12-14 in the MSDN article by opening the AssemblyInfo.cs file (contained in the Properties folder of the project). Add this line at the bottom of the file: [assembly: TagPrefix("CustomControls", "CC")]
  5. In LinkButtonDefault.cs add this code to override the OnPreRender event:

code(注意使用 this.ClientID

Code (notice the use of this.ClientID):

    protected override void OnPreRender(EventArgs e)
    {
        string addClickFunctionScript = @"function addClickFunction(id) {
           var b = document.getElementById(id);
           if (b && typeof(b.click) == 'undefined')
             b.click = function() {
               var result = true;
               if (b.onclick) result = b.onclick();
               if (typeof(result) == 'undefined' || result)
                 eval(b.getAttribute('href'));
             }
         };";

        string clickScript = String.Format("addClickFunction('{0}');", this.ClientID);

        Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + this.ClientID, clickScript, true);

        base.OnPreRender(e);
    }

您可能还需要更新生成的属性code类的声明与开始[ToolboxData(&LT以上; {0} 使用 LinkBut​​tonDefault 而不是 ServerControl1 。这就是它为新的服务器控件项目。我强烈建议你阅读上述MSDN文章趁其他功能,如添加控件工具箱,如果你有一个这样做的必要。

You may also want to update the generated attribute code above the class declaration that starts with [ToolboxData("<{0}: to use LinkButtonDefault instead of ServerControl1. That's it for the new Server Control project. I highly recommend reading the aforementioned MSDN article to take advantage of other capabilities, such as adding controls to the toolbox if you have a need to do so.

在完成这些步骤,你应该有类似这样的 LinkBut​​tonDefault.cs 文件后:

After completing these steps you should have a LinkButtonDefault.cs file that resembles this:

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:LinkButtonDefault runat=server></{0}:LinkButtonDefault>")]
    public class LinkButtonDefault : LinkButton
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(Text);
        }

        protected override void OnPreRender(EventArgs e)
        {
            string addClickFunctionScript = @"function addClickFunction(id) {
               var b = document.getElementById(id);
               if (b && typeof(b.click) == 'undefined')
                 b.click = function() {
                   var result = true;
                   if (b.onclick) result = b.onclick();
                   if (typeof(result) == 'undefined' || result)
                     eval(b.getAttribute('href'));
                 }
             };";

            string clickScript = String.Format("addClickFunction('{0}');", this.ClientID);

            Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + this.ClientID, clickScript, true);

            base.OnPreRender(e);
        }
    }
}

现在返回到你的Web应用程序,并添加到 CustomControls 项目的引用。您应该能够从添加引用的做到这一点,因为我建议增加上述项目,以现有的解决方案项目设置页。如果你愿意,你可以已经建立了上述项目在其自己的解决方案,那么你会添加一个引用到它的的.dll 文件通过使用浏览设置页。一旦引用已经添加您准备使用新的 LinkBut​​tonDefault 控制。

Now return to your web application and add a reference to the CustomControls project. You should be able to do this from the Add Reference's Project tab since I suggested adding the above project to your existing solution. If you want you could've built the above project in its own solution then you would add a reference to it's .dll file by using the Browse tab. Once a reference has been added you are ready to use the new LinkButtonDefault control.

要使用的控件,您可以使用每个页面的控制将被用在@ Register指令,或者你可以将它添加到Web.config,并获得整个应用程序方便地看到它。我将在下面你展示这两种方法。根据您的问题,我想你会想要将它添加到Web.config。请参阅MSDN文章,你会发现这些信息中途倒的标签preFIX部分下的页面。

To use the controls you can use the @ Register directive on each page the control will be used, or you can add it to the Web.config and gain easy reference to it throughout your application. I will show you both methods below. Based on your question I think you'll want to add it to the Web.config. Refer to the MSDN article and you will find this information half way down the page under "The Tag Prefix" section.

使用@注册指令:

转到所需的的.aspx 页和注册指令添加到您想要的每个页面的顶部使用控制:

Go to your desired .aspx page and add the Register directive to the top of each page you want to use the control in:

<%@ Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="CC" %>

在同一个页面,你现在可以使用该控件的多个实例。这里有一个例子:

On the same page, you may now use multiple instances of the control. Here's an example:

<p><strong>1st Panel:</strong></p>
<asp:Label runat="server" ID="helloLabel" />
<asp:Panel ID="Panel1" runat="server" DefaultButton="lbHello">
    First name:
    <asp:TextBox runat="server" ID="txtFirstName" />
    <CC:LinkButtonDefault ID="lbHello" runat="server" Text="Click me" OnClick="lbHello_Click"
        OnClientClick="alert('Hello, World!');" />
</asp:Panel>

<p><strong>2nd Panel:</strong></p>
<asp:Label runat="server" ID="fooBarLabel" />
<asp:Panel ID="Panel2" runat="server" DefaultButton="lbFooBar">
    Other:
    <asp:TextBox runat="server" ID="TextBox1" />
    <CC:LinkButtonDefault ID="lbFooBar" runat="server" Text="Click me" OnClick="lbFooBar_Click" />
</asp:Panel>

在后面的( .aspx.cs ),您将需要添加code:

In the code behind (.aspx.cs) you would need to add:

protected void Page_Load(object sender, EventArgs e)
{
    // example of adding onClick programmatically
    lbFooBar.Attributes.Add("onClick", "alert('Foo Bar!');"); 
}

protected void lbHello_Click(object sender, EventArgs e)
{
    helloLabel.Text = String.Format("Hello, {0}", txtFirstName.Text);
}

protected void lbFooBar_Click(object sender, EventArgs e)
{
    fooBarLabel.Text = String.Format("FooBar: {0}", TextBox1.Text);
}

使用Web.config文件:

要使用的Web.config保持在上面的例子中使用的完全一样的标记和code。请按照下列步骤:

To use the Web.config keep the exact same markup and code used in the above example. Follow these steps:


  1. 卸下在.aspx标记中使用了 @注册指令。

  2. 打开的Web.config 提交您的Web应用程序。

  3. 找到的&LT;&的System.Web GT; ...&LT; /system.web> 部分

  4. 添加下面的映射至该节:

  1. Remove the @ Register directive used on the .aspx markup.
  2. Open the Web.config file for your web application.
  3. Locate the <system.web>...</system.web> section.
  4. Add the following mapping to that section:

映射:

<pages>
  <controls>
    <add assembly="CustomControls" namespace="CustomControls" tagPrefix="CC" />
  </controls>
</pages>

重新编译,一切都应该成功打造。有了这个地方,你不再需要指定每个页面上的 @注册指令。

如果您遇到问题或有任何问题,让我知道。刚读了上面的一切,因为精心这是一个很长的帖子,有很多code的。

If you get stuck and have any questions let me know. Just read over everything above carefully since it's a long post with lots of code.

这篇关于在asp.net中可重复使用的Page_ preRender功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆