将 DataContext 传递给 UserControl

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

我有一个包含数据集的页面:

protected void Page_Load(object sender, EventArgs e)
{
     MyDefinedDataContext mydatacont = new MyDefinedDataContext();
}

我想将此数据上下文传递给

UserControl

<%@ Page Language="C#" MasterPageFile="~/Site2.Master" Inherits="WebApplication3._Default" %>
<%@ Register src="inc/Tabular.ascx" tagname="Tabular" tagprefix="testing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <testing:Tabular ID="tabularArticles" runat="server" currentPage="3" title="Articles"/>
</asp:Content>

我该怎么做?我会以某种方式在

UserControl
Page_Load
中做到吗?

protected void Page_Load(object sender, EventArgs e)
{
    myCtx = mydatacont;
    this.setPreInfo();
    this.getTableInfo();
    this.setTableMeta();
}
c# asp.net user-controls datacontext
3个回答
1
投票

您不需要将其传递给您的

UserControl
DataContext
对象的创建成本低廉,因此如果您需要访问该对象,只需实例化一个新对象即可。

但是,要直接回答您的问题,您可以通过将其存储在

HttpContext
中,在所有用户控件之间共享
DataContext
范围的
HttpContext.Items
,例如

  HttpContext.Items["DataContextKey"] = new MyDataContext();

然后,您可以在构造函数中初始化一个字段,就像从控件中通过

  _dataContext = (MyDataContext)Context.Items["DataContextKey"];

用于管理一般生命周期的此方法(和其他方法)的更优雅的实现可在

http://www.west-wind.com/weblog/posts/246222.aspx
中找到, DataContext 上课。

您最感兴趣的方法是:

DataContextFactory



0
投票


0
投票

static object GetWebRequestScopedDataContextInternal(Type type, string key, string connectionString) { object context; if (HttpContext.Current == null) { if (connectionString == null) context = Activator.CreateInstance(type); else context = Activator.CreateInstance(type, connectionString); return context; } // *** Create a unique Key for the Web Request/Context if (key == null) key = "__WRSCDC_" + HttpContext.Current.GetHashCode().ToString("x") + Thread.CurrentContext.ContextID.ToString(); context = HttpContext.Current.Items[key]; if (context == null) { if (connectionString == null) context = Activator.CreateInstance(type); else context = Activator.CreateInstance(type, connectionString); if (context != null) HttpContext.Current.Items[key] = context; } return context; }

让页面实现这个接口,并执行以下操作:

public interface IDataContextPage { MyDefinedDataContext DataContext { get; } }

您的用户控件可以通过界面引用此页面。在 UC 中执行此操作:

public class MyPage: Page, IDataContextPage { public MyDefinedDataContext DataContext { get { return _context; } } }

我建议在页面的 init 事件中创建上下文,而不是加载。

HTH.

© www.soinside.com 2019 - 2024. All rights reserved.