Is it possible to inject a Web User Control into another Web User Control?
I have a Web User Control on my web application (.NET Framework 3.5
, C#
) :
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Home.ascx.cs" Inherits="context_centro_Home" %>
<div class="main">
开发者_如何学运维Hello page
</div>
<%=strBuild %>
Now, the content of the string strBuild
is not produced by Home.ascx.cs
, but from Testo.ascx.cs
; so I think I need to inject the Testo's Web User Control
into Home
.
Is it possible? How can I do it?
You can put a user control, inside another user control in the same way you can put a user control in a page, i.e. in the markup. You don't need to "inject" anything.
The context will always be that of the current page and in order to use a variable that was defined in another page and/or user control, you will need to store it within the Session or pass as QueryString parameter (or similiar method of storing/retrieving data).
Yes it is possible but have some side effects.
// load the control
var oTesto = Page.LoadControl("Testo.ascx");
// here you need to run some initialization of your control
// because the page_load is not loading now.
// a string writer to write on it
using(TextWriter stringWriter = new StringWriter())
{
// a html writer
using(HtmlTextWriter GrapseMesaMou = new HtmlTextWriter(stringWriter))
{
// now render the control inside the htm writer
oTesto.RenderControl(GrapseMesaMou);
// here is your control rendered output.
strBuild = stringWriter.ToString();
}
}
Other possible way, is to place a place holder there, and after you load the control, you add it to the place holder, but since you have a string in your question, I type it this way.
This is pretty Ugly, but should work :
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Home.ascx.cs" Inherits="context_centro_Home" %>
<uc1:Testo id="Testo1" runat="Server" Visible="false" />
<div class="main">
Hello page
</div>
<%=Testo1.strBuild %>
Having suggested a fairly ugly solution, I would go further to say you may want to consider changing your architecture here - as I'm not 100% clear opn what you are trying to acheive I'm not quite sure what to suggest! But, at the end of the day, the content of the strBuild variable should probably be populated in a Third user Control that is then used in both Testo and Home user controls. e.g.:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Home.ascx.cs" Inherits="context_centro_Home" %>
<div class="main">
Hello page
</div>
<uc1:strBuild id="strBuild1" runat="Server" />
where strBuild Control looks like :
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="strBuild.ascx.cs" Inherits="context_centro_strBuild" %>
<%=strBuild %>
Make sense ?
Anyway, hope that helps, Dave
精彩评论