I am trying the following:
public partial class PopUps : System.Web.UI.Page {
public string GetContentFromPlaceHolder(string strContentId) {
HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter());
plcPlaceHolderToGet.RenderControl(writer);
string strHtml = writer.InnerWriter.ToString();
return strHtml;
}
public static string GetContent() {
PopUps puToUse = new PopUps();
string strHtml = puToUse.GetContentFromPlaceHolder();
return strHtml;
}
}
However, when I run the static method GetContent from another page I get this error:
object reference not set to an instance of an object
on the line
plcPlaceHolderToGet.RenderControl(writer);
The ID of the control is correct, it just seems like I need to run some kind of instantiation of the controls on the Page before I can get the HTML of one of the controls.
What am I missing?
The design view of the page looks like this
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PopUps.aspx.cs" Inherits="PopUps" %>
<asp:PlaceHolder runat="server" id="plcPlaceHolderToGet">
<div>
Some more HTML...
</div>
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" id="plcAnotherPlaceHolder">
<div>
Some more HTML...
</div>
</asp:PlaceHolder>
I am trying to do this to have one place to hold all my HTML. HTML, that sometimes needs to be fetched from other C# code and sometimes through an AJAX call.
I solved it like this:
HtmlBits.aspx:
The two only methods of HtmlBits.aspx.cs:
HtmlBitsContent.ascx:
The backend of HtmlBitsContent.ascx:
Now the different HTML bits can be called via code in some other random .cs file:
or
However the HTML bits can also be fetched via AJAX in some random JavaScript-file (here shown with jQuery):
Please note that all of the code above is only to give a general idea of what I did.
It’s not plug n’ play but definitely useful if someone else needs to maintain some small HTML snippets and fetch them from several different places.
It’s even possible to input some arguments to show in the HTML through the GetArg method.
Enjoy 🙂