【问题标题】:Dynamic user control controls are null on load动态用户控制控件在加载时为空
【发布时间】:2012-01-09 23:42:59
【问题描述】:

我的 ASP.Net 应用程序中有一个基本用户控件,此用户控件中有 HTML 标记,设置为 runat="server" 和 id。我遇到的问题是当加载用户控件时,HTML 标记被返回为 null

ASP.Net C# 代码:

public partial class webonlinecustombase : System.Web.UI.UserControl
{
    public Event Event { get; set; }
    public OnlineSystemPageCustom custompage { get; set; }
    public OnlineSystemPageCustom.OnlineSystemPageHdr.OnlineSystemPageModule custommodule { get; set; }

    public void Page_Load(object sender, EventArgs e)
    {
        string typeName = custommodule.ModuleInternetFile;
        inpagelink.HRef = "#" + custommodule.ModuleName.Replace(" ", "").Replace("/", "");
        modtitle.InnerText = custommodule.ModuleName;
        Type child = Type.GetType(typeName);
        UserControl ctl = Activator.CreateInstance(child) as UserControl;
        if (ctl != null)
        {
            this.modsection.Controls.Add(ctl);
        }
    }
}

这是 HTML 标记:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="webonlinecustombase.ascx.cs" Inherits="IPAMIntranet.IPAM_Controls.webtemplatecontrols.webonlinecustombase" %>
<a id="inpagelink" runat="server"></a>
<span id="modtitle" runat="server" style="width:100%;text-align:left">Scientific Overview</span>
<div id="modsection" runat="server" style="width:100%;">
</div>
<p><a href="#top" class="bodylink">Back to Top</a></p>

为什么inpagelinkmodtitle 返回为空?

【问题讨论】:

  • 您不应该将 UserControl 作为 Page.LoadControl("...") 作为 UserControl 加载而不是激活它的类型吗?
  • webonlinecustombase 是这样加载的,但是从它继承的控件是完全动态的,所以我不知道要调用哪些控件。我还能将 Page.LoadControl 用于动态控件吗?

标签: c# asp.net dynamic user-controls null


【解决方案1】:

我在 Web 应用程序(不是网站)中看到这种情况发生在对源进行更改时(尤其是在以前不是 runat=server 的项目上设置 runat=server),但您没有切换到设计器视图.

我解决此问题的方法是切换到设计视图并弄脏其中一个字段中的属性。这通常会导致 VS 更新设计器代码隐藏文件。

您可以仔细检查此文件以确保已添加控件。如果您在执行此操作之前检查它,您应该会发现它们丢失了。

【讨论】:

    【解决方案2】:

    asp.net 没有 span 类,所以你不能用它在后面的代码中做任何事情。

    使用 LinkBut​​ton 或 HyperLink 代替

    另一种解决方案是在代码中创建 span 或 a,类似这样

    var span = new HtmlGenericControl("span");
    span.InnerHtml = "From<br/>Date";
    span.Attributes["class"] = "blue";
    placeholder.Controls.Add(span);
    

    希望我能帮上忙 :))

    【讨论】:

    • 事实上你不能在代码中用 span 或 div 做任何事情。那是完全错误的。只要您有一个 ID 和 runat="server"
    • 我的错,我认为你不能从代码后面做任何事情,因为没有明确定义跨度类,但是当你从跨度后面的代码中调用它时是 HtmlGenericControl 类......对不起
    猜你喜欢
    • 2023-04-10
    • 2011-05-17
    • 1970-01-01
    • 2018-01-14
    • 2011-08-01
    • 2010-12-18
    相关资源
    最近更新 更多