在C#代码中包含HTML文件

时间:2009-05-20 12:32:53

标签: c#

我的页面中有左侧菜单。这个左侧菜单是一个HTML文件[LeftFrame.htm],使用以下代码包含在aspx页面中。

<!-- #include file="LeftFrame.htm"-->

现在我需要从C#代码将文件名更改为LeftFrameOthers.htm。

例如:

if ( arg == 1 )
{
    divMenu.InnerHTML = "<!-- #include file="LeftFrame.htm"-->";
}
else
{
     divMenu.InnerHTML = "<!-- #include file="LeftFrameOthers.htm"-->";
}

但它会产生错误并且未加载左侧菜单。有没有办法从C#代码管理它。

我不想为此目的使用两个div,如..

<div id="divOwnLeftFrame" runat="server" style="DISPLAY: block">
           <!-- #include file="LeftFrame.htm"--></div><div id="divOthersLeftFrame" runat="server" style="DISPLAY: block">
          <!-- #include file="LeftProfileFrame.htm"-->
</div>

并从C#代码更改div的显示属性。

我正在使用VS 2003

5 个答案:

答案 0 :(得分:2)

您可以创建一组LeftFrame用户控件,您可以在代码隐藏中替换它们。这样,您可以动态选择在运行时加载哪个控件。

例如。 。

ILeftFrame {}

LeftFrame : ILeftFrame {}
LeftFrameOthers : ILeftFrame {}

然后,控件本身

LeftFrameControl : System.Web.Ui.UserControl {}

然后,在您的页面中,您有一个

<myns:LeftFrameControl runat="Server">.

该控件将具有一个属性,允许您指定正在使用的ILeftFrame,将加载它,执行适当的行为,并且所有这些都将面向对象。

答案 1 :(得分:1)

一些肮脏的方式可能是做这样的事情:

<div id="ALeftMenu">
<%

if ( arg == 1 )
{
    %>
    <!-- #include file="LeftFrame.htm"-->";
    <%
}
else
{
     %>
     <!-- #include file="LeftFrameOthers.htm"-->
     <%
}

%>
</div>

不完美但快速,简单并且可以做到这一点。

答案 2 :(得分:1)

在ASP.NET中使用包含文件通常已被更强大的用户控件所取代。这是使用包含文件的另一种选择:

ASPX:

<asp:Literal ID="FrameLiteral" runat="server" />

代码背后:

private string GetFrameContent(int arg)
{
    string filename = (arg == 1) ? "LeftFrame.htm" : "LeftFrameOthers.htm";
    string path = Server.MapPath("./" + filename);
    string content = System.IO.File.ReadAllText(path);

    return content;
}

// Populate Literal
FrameLiteral.Text = GetFrameContent(arg);

不像使用用户控件那样优雅,但它应该完成工作并且相对整洁。

答案 3 :(得分:0)

ASP.NET Literal Control似乎是出于此目的的理想选择。代码几乎与您发布的内容相同:

<强>标记

<div id="divOwnLeftFrame" runat="server" style="display: block;">
    <asp:Literal id="menuLiteral" runat="server" Mode="PassThrough" />
</div>

代码隐藏(简化)

menuLiteral.Text = String.Format("<!-- #include file="LeftFrame{0}.htm"-->", 
    (arg == 1) ? "" : "Others";

如果能胜任,请告诉我。

答案 4 :(得分:0)

另一种选择可能是......

HTML:

<div style="DISPLAY: block">
    <asp:placeholder id=="phContent1" runat="server" visible="false">
        <!-- #include file="LeftFrame.htm"-->
    </asp:placeholder>
    <asp:placeholder id=="phContent2" runat="server" visible="false">
        <!-- #include file="LeftFrameOthers.htm"-->
    </asp:placeholder>
</div>

您的C#代码:

if ( arg == 1 )
{
    phContent1.Visible = true;
}
else
{
    phContent2.Visible = true;
}