简体   繁体   English

ASP.Net c# - 如何在App_Code类中实例化WebUserControl的实例?

[英]ASP.Net c# - How do I instantiate an instance of a WebUserControl from within a App_Code class?

Aloha, 阿罗哈,

I have a custom control that I need to instantiate from within a class and add to a page. 我有一个自定义控件,我需要在类中实例化并添加到页面。 My class has a function that I pass the Page to so i have access to the controls on the page. 我的类有一个函数,我传递了Page ,所以我可以访问页面上的控件。 I'm using this method to add standard ASP controls already and everything it working as expected. 我正在使用这种方法添加标准的ASP控件以及它按预期工作的一切。 My problem is that the type for the custom control is know defined? 我的问题是自定义控件的类型是已知定义的?

I read here to move the .cs from the control into the App_Code folder but when I do that it won't compile as it doesn't see the controls in the ascx as valid. 在这里阅读将.cs从控件移动到App_Code文件夹中,但是当我这样做时它不会编译,因为它没有看到ascx中的控件有效。 For example I get CS0103: The name 'litTest' does not exist in the current context . 例如,我得到CS0103: The name 'litTest' does not exist in the current context So as they are partial classes I created a new empty partial class in the App_Code folder and left the control's .cs file alone. 因为它们是部分类,我在App_Code文件夹中创建了一个新的空部分类,并单独留下控件的.cs文件。

Well it compiles this way but when I add the control to the Page.controls collection, I dont see anything on the page where it should be. 好吧它以这种方式编译但是当我将控件添加到Page.controls集合时,我在页面上看不到它应该是什么。 For example I added TEST to the bottom of the ascx file, it I dont see it on the page. 例如,我将TEST添加到ascx文件的底部,我在页面上看不到它。 Additionally the control has variables that I need to set that I don't have access to when using the empty partial class. 此外,控件还有我需要设置的变量,在使用空的分部类时我无权访问。

I know that what I am trying to do works with standard controls, why can't I seem to make this work with a custom control? 我知道我想要做的是使用标准控件,为什么我似乎无法使用自定义控件?

My partial class in the App_Code folder: 我在App_Code文件夹中的部分类:

public partial class CustomControlClass : System.Web.UI.UserControl
{

}

My partial class in for the user control: 我为用户控件的部分课程:

public partial class CustomControlClass : System.Web.UI.UserControl
{
    private int _myValue= -1;
    public int myValue
    {
        get { return _myValue; }
        set { _myValue= value; }
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        litTest.Text = "TEST";
    }
}

My user control ascx: 我的用户控件ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustomControlClass.ascx.cs" Inherits="CustomControlClass" %>
<asp:Literal ID="litTest" runat="server"></asp:Literal>
TEST

My App_Code class: 我的App_Code类:

public class MyClass
{
    public static void doWork(Page Ctrl)
    {
        CustomControlClass c = new CustomControlClass();
        //c.myValue = 1;  // Wont compile with this line
        Ctrl.Controls.Add(c);

        Literal l = new Literal();
        l.Text = "HELLO";
        Ctrl.Controls.Add(l);
    }
}

The page output does not have the word TEST on it at all. 页面输出根本没有单词TEST。 The word HELLO shows up just fine. HELLO这个词显示得很好。 I've tried calling the MyClass.doWork() from the pages Load , Init and PreInit callbacks, all result in the dame thing. 我试过从页面LoadInitPreInit回调中调用MyClass.doWork() ,这些都导致了dame的事情。

Update: 更新:

As Minh Nguyen suggested I can use Ctrl.LoadControl("~/Controls/CustomControlClass.ascx"); 正如Minh Nguyen建议我可以使用Ctrl.LoadControl("~/Controls/CustomControlClass.ascx"); to load the control but I can not cast it as its own type I have to assign it as a Control type: 加载控件但我无法将其转换为自己的类型我必须将其指定为控件类型:

Control c= Ctrl.LoadControl("~/Controls/CustomControlClass.ascx");

Doing this will let me add the control to the page and have it work as expected. 这样做可以让我将控件添加到页面并使其按预期工作。 The down side is that I have no access to any of the controls properties. 缺点是我无法访问任何控件属性。 To solve this i am doing this: 为了解决这个问题,我这样做:

c.GetType().GetProperty("myValue").SetValue(c, 1, null);

This works, but I'm not sure how expensive that it to use. 这有效,但我不确定它的使用价格有多贵。 I wish I could just cast the control but I get an error when I try. 我希望我能投出控件,但是当我尝试时会出错。

I'm leaving this unanswered for a bit to see if there are any other options. 我暂时没有回答,看看是否还有其他选择。

Use 使用

CustomControlClass c = (CustomControlClass)Ctrl.LoadControl("~/VirtualPathToASCX/CustomControlClass.ascx");

instead of 代替

CustomControlClass c = new CustomControlClass();

UPDATE: fix cast bug 更新:修复投射错误

//LoadControl
ASP.customcontrolclass_ascx c = (ASP.customcontrolclass_ascx)this.LoadControl("~/Controls/CustomControlClass.ascx");
//set myValue
c.myValue = 3;

you can't see ASP.customcontrolclass_ascx type in VS AutoComplete List but it compiled with no error. 您无法在VS自动完成列表中看到ASP.customcontrolclass_ascx类型,但它编译时没有错误。

not sure what's going on with your code, but using mostly what you showed works for me: 不知道你的代码发生了什么,但主要使用你所展示的内容对我有用:

~/controls/testControl.ascx : 〜/ controls / testControl.ascx

<%@ Control Language='C#' AutoEventWireup='false' 
  Inherits='CustomControlClass' 
%>
<asp:Literal ID='litTest' runat='server'></asp:Literal>

.aspx page : .aspx页面

<%@ Page Language='C#' %>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<script runat='server'>
protected override void OnInit(EventArgs e) {
  base.OnInit(e);
  MyClass.doWork(this.Page);
}
</script>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head runat='server'><title></title></head>
<body><form id='form1' runat='server'>
</form></body></html>

~/app_code/CustomControlClass.cs : 〜/ app_code / CustomControlClass.cs

using System;
using System.Web;
using System.Web.UI.WebControls;

public partial class CustomControlClass : System.Web.UI.UserControl {
  private int _myValue= -1;
  public int myValue {
    get { return _myValue; }
    set { _myValue= value; }
  }
  private Literal _litTest;
  public Literal litTest {
    get { return _litTest; }
    set { _litTest= value; }

  }
  protected override void  OnInit(EventArgs e) {
    base.OnInit(e);
    litTest.Text = "TEST";
  }
}

~/app_code/MyClass : 〜/ app_code / MyClass

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public class MyClass {
  public static void doWork(Page Ctrl) {
    CustomControlClass c = 
      (CustomControlClass) Ctrl.LoadControl("~/controls/testControl.ascx");
    c.myValue = 1;
    Ctrl.Form.Controls.Add(c);

    Literal l = new Literal();
    l.Text = string.Format(
      "<p>CustomControlClass.myValue: {0} </p>", 
      c.myValue
    )
    + string.Format(
      "<p>CustomControlClass.litTest.Text: {0} </p>", 
      c.litTest.Text
    )
    ;
    Ctrl.Form.Controls.Add(l);
  }
}

in other words the cast to CustomControlClass when calling LoadControl() works for me. 换句话说,当调用LoadControl()时,转换为CustomControlClass对我有用 if i understood you correctly that's the problem? 如果我理解你是正确的问题?

A different way of LoadControl which works (only .NET 4 tested) 一种不同的LoadControl方式(仅测试.NET 4)

Usage is as follows in any page you can call 您可以调用的任何页面中的用法如下

protected void Page_Load(object sender, EventArgs e)
{
    Control ctrl = SomeClass.GetNewUserControl( "hello add me");

    Panel1.Controls.Add(ctrl);
}

~/app_code/BaseMyControls.cs: 〜/的app_code / BaseMyControls.cs:

using System;
using System.Collections.Generic;
using System.Web;

/// <summary>
/// Summary description for BaseMyControls
/// </summary>
public class BaseMyControls  : System.Web.UI.UserControl
{
    public string strProperty;

    public BaseMyControls()
    {

    }
}

~/app_code/SomeClassInApp_Code.cs: 〜/的app_code / SomeClassInApp_Code.cs:

using System;
using System.Collections.Generic;
using System.Web;

/// <summary>
/// Summary description for SomeClassInApp_Code
/// </summary>
public class SomeClassInApp_Code
{
    public static System.Web.UI.Control GetNewUserControl(string someString)
    {
        BaseMyControls bc = (BaseMyControls)(new System.Web.UI.UserControl()).LoadControl("~/controls/MyUC.ascx");
        bc.strProperty = someString;
        return bc;
    }
}

~/controls/MyUC.aspx: 〜/控制/ MyUC.aspx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyUC.ascx.cs" Inherits="MyUC" %>
<asp:Label runat="server" ID="lbl" /></asp:Label>

~/controls/MyUC.aspx.cs: 〜/控制/ MyUC.aspx.cs:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MyUC : BaseMyControls
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string a = this.strProperty;

        lbl.Text = a;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从app_code中的类设置母版页中的属性? 与asp.net C# - How to set property in master page from class in app_code? with asp.net c# 如何从App_Code引用ASP.net MasterPage - How do I reference an ASP.net MasterPage from App_Code 如何从C#App_Code类中获取当前页面的URL? - How can I get the URL of the current page from within a C# App_Code class? 我可以在ASP.NET网站的CodeFile之外的App_Code的C#文件中使用类/函数吗? - Can I use class/function in C# file in App_Code besides the CodeFile for an asp.net website? 为什么我不能在我的代码asp.net c#中使用app_code中的代码文件 - why I can't use code files from app_code in my code asp.net c# ASP.NET C#:如何在 web.config 中调用 App_code 函数 - ASP.NET C#: How can I call App_code functions inside of web.config ASP.NET中的类App_Code中的局部类 - Class in ASP.NET Partial Class in App_Code ASP.NET 核心 - 如何从我的 C# class 到我的 Z558B5744CF685F39D34EZ906B 客户端应用程序中获取我的状态代码? - ASP.NET Core - How do I get my status code from my C# class to my TypeScript Client App? C#ASP.net如何从后面的代码访问新类,而不是保留在APP_CODE中,而是与后面的代码保留在同一文件夹中 - C# ASP.net How to access new classes from code behind, not kept in APP_CODE, but kept in same folder as code behind 在ASP.Net App_Code文件夹中混合C#和VB.Net - Mixing C# and VB.Net in ASP.Net App_Code folder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM