简体   繁体   English

使用C#代码加载ascx组件

[英]Load ascx component using C# code

Is there any way that I can use C# to load and then "render" an ascx control? 有什么办法可以使用C#加载然后“渲染”ascx控件吗?

Essentially I am trying to replace inline ASP with a C# function which will return the same HTML. 本质上我试图用C#函数替换内联ASP,它将返回相同的HTML。 This would then let me set it as a webmethod so that I can update that section of the page with jQuery, using the same code that generated the original html. 然后,我可以将其设置为webmethod,以便我可以使用生成原始html的相同代码使用jQuery更新页面的该部分。

I really need some way of doing this, and this seems like a logical route. 我真的需要一些方法来做这件事,这似乎是一条合乎逻辑的路线。

You need to create a page in which you render the control: 您需要创建一个用于呈现控件的页面:

public static string RenderUserControl(string path)
{
    Page pageHolder = new Page();
    Control viewControl = pageHolder.LoadControl(path);

    pageHolder.Controls.Add(viewControl);
    using(StringWriter output = new StringWriter())
    {
        HttpContext.Current.Server.Execute(pageHolder, output, false);
        return output.ToString();
    }
}

A user control on its own will not render. 用户控件本身不会呈现。 ( This article has some related information from which I borrowed some code). 本文提供了一些相关信息,我借用了一些代码)。

Keltex's answer was the only that worked for me since i was working with nested user-controls. Keltex的回答是唯一对我有用的,因为我使用的是嵌套的用户控件。 Additionally, if you would want to pass parameters to your user control you can do so by: 此外,如果您想将参数传递给用户控件,可以通过以下方式执行此操作:

_MyNameSpace_MyUserControl viewcontrol = (_MyNameSpace_MyUserControl) pageHolder.LoadControl(path);

viewcontrol.MyParam = "My value";

I've not tried this, but you can load a control using the LoadControl function: 我没试过这个,但你可以使用LoadControl函数加载一个控件:

Control Example = LoadControl("~\\Controls\\MyControl.ascx");

Then you could try rendering the control: 然后你可以尝试渲染控件:

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Example.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

But make sure that you override VerifyRenderingInServerForm and switch EnableEventValidation to false on the page. 但请确保在页面上覆盖VerifyRenderingInServerForm并将EnableEventValidation切换为false。

Forget what I wrote above. 忘记我上面写的内容。 I went back and tested and you can't call LoadControl because the webmethod is static. 我回去测试了,你不能调用LoadControl,因为webmethod是静态的。 Since it's static you don't have a Page object to call... Which means no loading of user controls dynamically. 因为它是静态的,所以你没有要调用的Page对象......这意味着没有动态加载用户控件。

This Explanation should have the answers you are looking for. 这个解释应该有您正在寻找的答案。 Basically you have to declare the control in the page then LoadControl in the codebehind. 基本上你必须在页面中声明控件然后在代码隐藏中声明LoadControl。

它的使用非常简单:

yourItem.Controls.Add(LoadControl("~/user control File path"));

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM