【问题标题】:How to avoid hard-coding the Reference for a UserControl?如何避免对 UserControl 的参考进行硬编码?
【发布时间】:2013-03-31 05:32:12
【问题描述】:

我想知道是否有一种动态方法可以避免硬编码 UserControl 或“USING”的引用?

<%@ Reference Control="~/UserControl.ascx" %>
using UserControl;

我正在寻找一种方法,从后面的代码中动态地将对 UserControls 的引用添加到页面中。

【问题讨论】:

  • stackoverflow.com/questions/3945324/… 可能会帮助您不仅可以动态添加,还可以处理动态生成的用户控件的事件
  • 不幸的是,他们都没有回答我的问题。我想避免硬编码引用 UserControl。
  • 你想要完成什么?这些引用在编译时使用,不是吗?您的代码在运行时才会被调用。
  • @bmm6o,我已将 UserControls 动态添加到页面,并使用 引用它们,到目前为止一切正常,但我没有不想硬编码引用它们。我也想让引用部分动态化。

标签: c# asp.net user-controls reference


【解决方案1】:

如果我正确理解了您的问题,这应该可以满足您的要求-

默认.aspx

<!DOCTYPE html>
<html>
<head runat="server">
    <title>Dynamic User Control Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Dynamic User Control Test</h1>
        <asp:PlaceHolder ID="UserControlPlaceHolder" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

默认.aspx.cs

using System;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        UserControl uc = Page.LoadControl("~/UserControl.ascx") as UserControl;

        if (uc != null)
        {
            UserControlPlaceHolder.Controls.Add(uc);
        }
    }
}

用户控件.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControl.ascx.cs" Inherits="UserControl" %>

<p>Here is some content inside the user control</p>

UserControl.ascx.cs(如果 UserControl 是静态的并且不包含特定于解决方案的代码,则不需要)

using System;

public partial class UserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

这仅适用于动态添加到页面的控件。

【讨论】:

  • 嗨,感谢您的详细回答:) 很奇怪,您的无参考解决方案适用于一个 UserControl,但不适用于另一个。我已经检查了所有的东西。 string moduleName = drRegionModules["ModuleName"].ToString(); var uc = new Control(); switch (moduleName) { case "Contents": uc = LoadControl(string.Format("~/uc/uc{0}.ascx", moduleName)) as ucContents;休息; case "Menu": uc = LoadControl(string.Format("~/uc/uc{0}.ascx", moduleName)) as ucMenu;休息; }
  • 我忘了提到它将 ucMenu 识别为类,但返回 ucContents 错误。
猜你喜欢
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 2022-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多