您的位置:首页 > 其它

Response.Write输出导致页面变形

2010-12-19 10:44 411 查看
Response.Write方法会造成页面模型混乱,字体变大没有样式等问题。

解决:使用RegisterClientScriptBlock或RegisterStartupScript方法。

namespace Common
{
/// <summary>
/// 提示信息
/// </summary>
public class MessageBox
{
public static void Alert(Page page,string message)
{
if (!page.ClientScript.IsClientScriptBlockRegistered("demo"))
{
        //HttpContext.Current.Response.Write("<script>document.location=document.location;alert('" +message + "');</script>"); 网上有人使用这种解决方法,但重设document.location会重新加载页面。
   page.ClientScript.RegisterClientScriptBlock(page.GetType(), "demo", "<script>alert('" + message +"');</script>");
}
}
}
}

使用:

Common.MessageBox.Alert(this,"每位学生只能选择一个题目!");

DEMO,查看几种方法输出的位置区别:

后台文件,Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write("<script>alert('Hello'');</script>");

//this.ClientScript.RegisterStartupScript(this.GetType(), "demo", "<script>alert('" + "Hello" + "');</script>");
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "demo", "<script>alert('Hello'');</script>");
}
}

输出的页面:

Response.Write输出在页面内容上方。

<script>alert('Hello');</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"   

        value="/wEPDwULLTE2MTY2ODcyMjlkZAVpRcHibkbkAXYhTouZnL6SNJ8d" />
    </div>

   <div>

   </div>
</form>
</body>
</html>

RegisterStartupScript输出在ASP.NET页面底部,关闭元素</form>之前。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
  <form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"

        value="/wEPDwULLTE2MTY2ODcyMjlkZAVpRcHibkbkAXYhTouZnL6SNJ8d" />
    </div>

  <div>
   </div>
    <script>alert('Hello');</script>

  </form>
</body>
</html>

RegisterClientScriptBlock输出在ASP.NET页面中开启元素<form>之后。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"

        value="/wEPDwULLTE2MTY2ODcyMjlkZAVpRcHibkbkAXYhTouZnL6SNJ8d" />
    </div>

    <script>alert('Hello');</script>
   <div>
   </div>
</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: