【问题标题】:reusing methods used in one code behind page to another code behind page将一个页面后代码中使用的方法重用到另一个页面后代码
【发布时间】:2016-11-15 03:24:24
【问题描述】:

在我的 asp 页面中,我有一个下拉列表,其值正在从数据库中检索。为了检索下拉列表的值,我在页面后面的代码中编写了一个方法。

现在我还要在另一个 asp 页面中使用相同的下拉菜单。为此,我正在将相同的方法写入相应的后台代码以从数据库中检索值。

我想知道有什么方法可以让我重用代码隐藏页面中所需的方法吗?

例如。产品页面(asp page)

<tr>
    <td class="va-top">Type:</td>
    <td><asp:ListBox ID="listBox_ProductType" runat="server" Rows="1" Width="300px"></asp:ListBox></td>               
</tr>

aspx 页面

public void GetProductBillingType()
{
    try
    {
        DataTable dt = new DataTable();
        listBox_ProductType.ClearSelection();
        DAL_Product_Registration objDAL = new DAL_Product_Registration();
        dt = objDAL.Get_ProductBillingType();
        if (dt != null && dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                listBox_ProductType.Items.Add(new ListItem(row["billing_sub_type"].ToString(), row["billing_dtls_id"].ToString()));
            }
        }
    }
    catch (Exception ex) { }
}

现在在另一个页面中,我必须使用相同的下拉菜单。我也在页面后面的另一个代码中编写相同的方法。

但是有什么方法可以重用 aspx 页面中使用的方法。

【问题讨论】:

  • 您可以将方法定义为静态类中的静态方法,并可以从那里调用该方法。有意义吗?
  • @lukai 感谢您的回答。但是请您用一些代码示例来解释您的回复。这会很有帮助。谢谢!

标签: c# asp.net


【解决方案1】:

您可以创建一个静态类并将您的帮助代码保存在那里。这样你就不需要重新发明轮子了。创建静态类的原因是您不需要创建实例来访问类方法。 这是一个例子。

public static class HelperMethods
{
    public static void GetProductBillingType(ListBox listBox)
    {
        try
        {
            DataTable dt = new DataTable();
            listBox.ClearSelection();
            DAL_Product_Registration objDAL = new DAL_Product_Registration();
            dt = objDAL.Get_ProductBillingType();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    listBox.Items.Add(new ListItem(row["billing_sub_type"].ToString(), row["billing_dtls_id"].ToString()));
                }
            }
        }
        catch (Exception ex) { }
    }
}

现在,您可以通过调用方法在其他地方使用此方法。将要添加数据的列表框作为参数传递。

HelperMethods.GetProductBillingType(list_box_where_you_want_to_add_data);

【讨论】:

    【解决方案2】:

    尝试将此功能提取到一些其他方法,该方法将相关列表框作为参数。

    例如:

    public class Helper
    {
        public static void GetProductBillingType(ListBox lb)
        {
           ...
        }
    }
    

    在你的aspx代码后面:

    public void GetProductBillingType()
        {
           Helper.GetProductBillingType(listBox_ProductType);
        }
    

    在另一个 aspx 页面中:

    public void GetOtherBillingType()
        {
           Helper.GetProductBillingType(listBox_OtherType);
        }
    

    【讨论】:

      【解决方案3】:

      这个问题的重点是将代码的可重用部分提取到另一个类(如实用程序或帮助程序类)中的方法中,并从那些代码行为页面访问此方法。此外,您可以使用 resharper 之类的工具来向您推荐如何更好地编码。

      【讨论】:

        猜你喜欢
        • 2011-01-16
        • 1970-01-01
        • 2015-07-11
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多