Export (0) Print
Expand All

@ Reference 

Indicates that another user control, page source file, or arbitrary file located at some virtual path should be dynamically compiled and linked against the current ASP.NET file (Web page, user control, or master page) in which this directive is declared.


<%@ Reference Page="path to .aspx page"
   Control="path to .ascx file"
   virtualPath="path to file" %>

Page

The external page that ASP.NET should dynamically compile and link to the current file that contains the @ Reference directive.

Control

The external user control that ASP.NET should dynamically compile and link to the current file that contains the @ Reference directive.

virtualPath

The virtual path for the reference. Can be any file type as long as a build provider exists. For example, it would be possible to point to a master page.

Using this directive allows you to dynamically compile a page, a user control, or another type of file that is associated with a build provider, and link it to the current Web page, user control, or master page file that contains the @ Reference directive. This allows you to reference the external compiled object and its public members from within the current file.

The following code example demonstrates using this directive to link a user control and load it to a containing page using the LoadControl method. The first part of the code is a simple user control. You should place this code in a new file, and name it MyControl.ascx. The second part of the code is a page that references the user control. When it is loaded to the page, the user control's LabelText value is set, and the user control is added to a PlaceHolder server control's System.Web.UI.ControlCollection object through the System.Web.UI.Control.Controls property.

<%@ Control language="C#" ClassName="MyControl" %>
<script runat="server">
  
  private string _labelText;
  
  public string LabelText
  {
    get { return _labelText; }
    set
    {
      if(!String.IsNullOrEmpty(value))
        _labelText = Server.HtmlEncode(value);
    }
  }

  void label1_init(object sender, EventArgs e)
  {
    label1.Text = LabelText;
  }
</script>

<asp:label id="label1" runat="server" Text="" 
  oninit="label1_init" />


<%@ Page language="C#" %>
<%@ Reference Control="MyControl.ascx" %>
<script runat="server">

  void Page_Load(Object sender, EventArgs e) 
  {
    MyControl ctrl = (MyControl) Page.LoadControl("MyControl.ascx");
    ctrl.LabelText = "Hello World!";
    PlaceHolder.Controls.Add(ctrl);
  }

</script>

<html>
   <body>
      <asp:placeholder id="PlaceHolder" runat="server" />
   </body>
</html>

Community Additions

ADD
Show:
© 2014 Microsoft