通过静态方法获取控件的 HTML

发布于 2024-12-14 11:49:09 字数 1365 浏览 2 评论 0原文

我正在尝试以下操作:

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;

    }

}

但是,当我从另一个页面运行静态方法 GetContent 时,我收到此错误:

未将对象引用设置为对象的实例

对象引用未设置为线上

plcPlaceHolderToGet.RenderControl(writer);

的 ID 是正确的,似乎我需要在页面上运行某种控件的实例化,然后才能获取其中一个控件的 HTML 。

我缺少什么?

页面的设计视图看起来像这样,

<%@ 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>

我试图这样做是为了有一个地方来保存我的所有 HTML。 HTML,有时需要从其他 C# 代码中获取,有时需要通过 AJAX 调用获取。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

或十年 2024-12-21 11:49:09

我这样解决了它:

HtmlBits.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HtmlBits.aspx.cs" Inherits="HtmlBits" %>
<%@ Register TagPrefix="testUC" TagName="PopupContent" Src="~/usercontrols/HtmlBitsContent.ascx" %>
<testUC:PopupContent id="popupMain" runat="server" />

HtmlBits.aspx.cs 的两个唯一方法:

public static string GetHtml(string strContentId, NameValueCollection args = null) {

    string strHtml = "";

    // Find the requested Placeholder in the usercontrol
    Page pageTemp = new Page();
    HtmlBitsContent popupContentControl = (HtmlBitsContent)pageTemp.LoadControl(Server.MapPath("/usercontrols/HtmlBitsContent.ascx"));
    popupContentControl.ExtraArguments = args;
    PlaceHolder plcHolder = (PlaceHolder)popupContentControl.FindControl("plc" + strContentId);

    // Could the Placeholder be found?
    if (plcHolder != null) {

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        Html32TextWriter hw = new Html32TextWriter(sw);

        plcHolder.RenderControl(hw);
        strHtml = hw.InnerWriter.ToString();

    }

    return strHtml;

}

public static void ShowHtml(string strContentId, NameValueCollection args = null) {

    string strHtml = GetHtml(strContentId, args);
    HttpContext.Current.Response.Write(strHtml);

}

HtmlBitsContent.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HtmlBitsContent.ascx.cs" Inherits="HtmlBitsContent" %>

<!-- HtmlBit1 -->
<asp:PlaceHolder runat="server" id="plcHtmlBit1">
    <div>
    Some html
    </div>
</asp:PlaceHolder>


<!-- HtmlBit2 -->
<asp:PlaceHolder runat="server" id="plcHtmlBit2">
    <div>
    Some other html
    </div>
</asp:PlaceHolder>

HtmlBitsContent.ascx 的后端:

public NameValueCollection ExtraArguments = null;

protected void Page_Load(object sender, EventArgs e) {

    string strContentId = Request.Querystring("contentid");

    PlaceHolder plcHolderToGet = (PlaceHolder)this.FindControl("plc" + strContentId);
    string strHtml = "";

    if (plcHolderToGet != null) {

        HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter());
        plcHolderToGet.RenderControl(writer);
        strHtml = writer.InnerWriter.ToString();

    }
    Response.Write(strHtml);
    Response.End();

}

public string GetArg(string strKey) {

    string strArgumentValue = "";

    strArgumentValue = Request.Querystring(strKey);

    if (ExtraArguments != null) {
        if (ExtraArguments[strKey] != null) {
            strArgumentValue = ExtraArguments[strKey];
        }
    }

    return strArgumentValue;
}

现在可以通过其他随机 .cs 文件中的代码调用不同的 HTML 位:

HtmlBits.ShowHtml("HtmlBit1");

或者

string strHtml = HtmlBits.GetHtml("HtmlBit1");

然而,HTML 位也可以通过 AJAX 在一些随机 JavaScript 文件中获取(此处使用 jQuery 显示):

$.ajax({
    url : '/htmlbits.aspx?contentid=HtmlBit1',
    success : function(responseHtml) {
        $('#containerElement').html(responseHtml);
    }
});

请注意,上面的所有代码只是大致了解我所做的事情。
它不是即插即用的,但如果其他人需要维护一些小的 HTML 片段并从几个不同的地方获取它们,那么它绝对有用。
甚至可以通过 GetArg 方法输入一些参数以在 HTML 中显示。

享受 :)

I solved it like this:

HtmlBits.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HtmlBits.aspx.cs" Inherits="HtmlBits" %>
<%@ Register TagPrefix="testUC" TagName="PopupContent" Src="~/usercontrols/HtmlBitsContent.ascx" %>
<testUC:PopupContent id="popupMain" runat="server" />

The two only methods of HtmlBits.aspx.cs:

public static string GetHtml(string strContentId, NameValueCollection args = null) {

    string strHtml = "";

    // Find the requested Placeholder in the usercontrol
    Page pageTemp = new Page();
    HtmlBitsContent popupContentControl = (HtmlBitsContent)pageTemp.LoadControl(Server.MapPath("/usercontrols/HtmlBitsContent.ascx"));
    popupContentControl.ExtraArguments = args;
    PlaceHolder plcHolder = (PlaceHolder)popupContentControl.FindControl("plc" + strContentId);

    // Could the Placeholder be found?
    if (plcHolder != null) {

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        Html32TextWriter hw = new Html32TextWriter(sw);

        plcHolder.RenderControl(hw);
        strHtml = hw.InnerWriter.ToString();

    }

    return strHtml;

}

public static void ShowHtml(string strContentId, NameValueCollection args = null) {

    string strHtml = GetHtml(strContentId, args);
    HttpContext.Current.Response.Write(strHtml);

}

HtmlBitsContent.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HtmlBitsContent.ascx.cs" Inherits="HtmlBitsContent" %>

<!-- HtmlBit1 -->
<asp:PlaceHolder runat="server" id="plcHtmlBit1">
    <div>
    Some html
    </div>
</asp:PlaceHolder>


<!-- HtmlBit2 -->
<asp:PlaceHolder runat="server" id="plcHtmlBit2">
    <div>
    Some other html
    </div>
</asp:PlaceHolder>

The backend of HtmlBitsContent.ascx:

public NameValueCollection ExtraArguments = null;

protected void Page_Load(object sender, EventArgs e) {

    string strContentId = Request.Querystring("contentid");

    PlaceHolder plcHolderToGet = (PlaceHolder)this.FindControl("plc" + strContentId);
    string strHtml = "";

    if (plcHolderToGet != null) {

        HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter());
        plcHolderToGet.RenderControl(writer);
        strHtml = writer.InnerWriter.ToString();

    }
    Response.Write(strHtml);
    Response.End();

}

public string GetArg(string strKey) {

    string strArgumentValue = "";

    strArgumentValue = Request.Querystring(strKey);

    if (ExtraArguments != null) {
        if (ExtraArguments[strKey] != null) {
            strArgumentValue = ExtraArguments[strKey];
        }
    }

    return strArgumentValue;
}

Now the different HTML bits can be called via code in some other random .cs file:

HtmlBits.ShowHtml("HtmlBit1");

or

string strHtml = HtmlBits.GetHtml("HtmlBit1");

However the HTML bits can also be fetched via AJAX in some random JavaScript-file (here shown with jQuery):

$.ajax({
    url : '/htmlbits.aspx?contentid=HtmlBit1',
    success : function(responseHtml) {
        $('#containerElement').html(responseHtml);
    }
});

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 :)

残龙傲雪 2024-12-21 11:49:09

由于您想在应用程序的各个位置重用 html,我建议创建一个 用户控制。

ASP.NET Web 表单中的每个请求都必须针对页面(或 HttpHandler)。因此,为了通过 ajax 访问您的控件,您需要将其添加到页面,然后从 javascript 请求它。

您可以使用 jQuery 的 $.get() 方法

$.get('path/to/your/page.aspx', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

Since you want to reuse html in various places in your app, I would recommend creating a User Control.

Every request in ASP.NET web forms must be to a page (or an HttpHandler). So in order to access your control via ajax, you'll need to add it to a page and then request it from javascript.

You could use jQuery's $.get() method:

$.get('path/to/your/page.aspx', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文