【问题标题】:How to code reuse apsx?如何代码重用apsx?
【发布时间】:2012-09-27 20:36:35
【问题描述】:

我知道在 C# 中我可以创建工厂,但我不知道如何在 aspx 中重用代码。我的代码最初只用于 ARList,但现在有 IcnList。我想过做一个 switch 语句,但没有更好的代码吗?

函数

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ARExtractionController arController = new ARExtractionController();
                Dictionary<int, string> ARDictionary = arController.GetTickets();
                List<int> sortedARList = new List<int>();
                foreach (KeyValuePair<int, string> kv in ARDictionary)
                {
                    sortedARList.Add(kv.Key);
                }
                sortedARList.Sort();
                sortedARList.Reverse();
                ARList.DataSource = sortedARList;
                ARList.DataBind();
                ARList.Items.Insert(0, " ");
                ARList.AutoPostBack = true;
            }
        }

【问题讨论】:

标签: c# asp.net .net design-patterns


【解决方案1】:

如果您只是希望能够重用代码,请将一个类添加到您的项目中以获取实用方法并将其转储到其中以供两个页面使用。

如果您尝试使用相关 UI 重用代码,请查看允许您这样做的用户控件(ascx 文件)。

从问题中不清楚哪个适合你。

【讨论】:

    【解决方案2】:

    在 TicketExtractionWeb 中,创建一个 BasePage 类。

    BasePage.cs:

    public class BasePage : System.Web.UI.Page
    {
        // Add methods that are used on all your pages in here.
    
        protected DateTime GetCurrentDate()
        {
            return DateTime.Now;
        }
    }
    

    还有一个页面(我们称之为MyPage):

    public class MyPage : BasePage
    {
        protected Page_Load(object sender, EventArgs e)
        {
            var currentDate = this.GetCurrentDate();
        }
    }
    

    所以当你创建另一个aspx页面时,它会默认为:

    public class MyNewPage : System.Web.UI.Page
    {
        // ...
    }
    

    只需将: System.Web.UI.Page 更改为: BasePage

    【讨论】:

      【解决方案3】:

      您应该能够从单个页面继承以重用代码。

      aspx 文件顶部:

      <%@ Page Language="C#" AutoEventWireup="true" Inherits="MyNamespace.CommonCode" %>
      

      【讨论】:

      • 你说的在技术上是正确的,但我认为它实际上不可能做到 OP 真正需要的。
      • @tomfanning 技术上正确。最好的一种正确!哦等等,我明白你的意思了。
      • 当然,除非你可以有多个 Inherits 属性! (我 98% 肯定你做不到)
      • @tomfanning 九小时前你在哪里。我们正在经历同样的事情,试图重用 aspx 文件中的代码。最终尝试在 dll 中嵌入 ascx 文件,然后放弃并尝试其他方法。
      • 这里的答案肯定只是“在项目中创建一个类”或“创建一个包含一些类的程序集并添加对它的引用”。 ASP.NET Web 应用程序项目没有什么特别之处...
      【解决方案4】:

      如果要复用html,请使用用户控制文件(.ascx),可以多次复用

      when do you need .ascx files and how would you use them?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        • 1970-01-01
        • 2019-08-20
        • 2013-06-23
        • 2018-12-17
        • 2015-08-07
        • 2011-08-29
        相关资源
        最近更新 更多