开发者

why Response.Write destroy align of the whole page?

My application use a masterpage which the ContentPlaceHolder align is center. But whenever, I use Response.Write() function to write something on screen, the whole page just changed to align left. I'm thinking, jquery ajax function could let me write html into some part of the page without destroy align. But I'd like to know if there is better solution. Any idea? Here's the code in code page:

 DirectoryInfo di = new DirectoryInfo("e:/asdf");
 FileInfo[] rgFiles = di.GetFiles("*.*");
 if (rgFiles != null)
 {
     sb.Append("<span class='SubTitle'>Your attachments list:</span>");
     foreach (FileInfo fi in rgFiles)
     {
         sb.AppendFormat("<br><a href='e:\\asdf\\" + fi.Name 开发者_StackOverflow社区+ "'>" 
                         + fi.Name + "</a>");
     }
 }
 Response.Write("<span style='position:absolute;top:200px;left:200px'>" 
                 + sb + "</span>");


Response.Write() writes data directly to the output stream, so depending om when you call it in the page life cycle, the data can end up enywhere on the page any destroy the markup.


Avoid using Response.Write() to add content to the page, rather, you should add content to a server control.

In the web form:

<div runat="server" id="test" class="someclass"></div>

In the code behind:

test.innerHTML += somecontent;

This will keep your content within the CSS definitions you set for that server control.


An easy way to do this is to place a Panel on your page and add a literal control to your panel like this:

myPanel.Controls.Add(new LiteralControl("Some text to write out"));

This way the text will appear exactly where the Panel is placed on the page.


I usually do this by adding a LiteralControl to a placeholder or panel asp control.

<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolder" Runat="Server">

for the aspx page (assuming you're using a master page here). and then:

LiteralControl lc = new LiteralControl("<h1>Some HTML</h1>");
this.Content1.Controls.Add(lc);

In your code-behind.

Or, if you just want to add it to a panel:

<asp:Panel ID="Panel1" runat="server"></asp:Panel>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜