1

My code below:

Test.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <input type="text" value="<%=HttpUtility.HtmlEncode(ab)%>" runat="server"/>
    </form>
</body>
</html>

Test.cs:

 public partial class Test: System.Web.UI.Page
    {
       public string ab;
        protected void Page_Load(object sender, EventArgs e)
        {
             ab = "<script>alert('111');</script>";
        }
    }

After running the test.aspx page,the textbox value is <%=HttpUtility.HtmlEncode(ab)%>

But remove the runat="server" string show correct!

4

1 回答 1

2

当你runat="server"对一个控件做a时,它变成了一个服务器控件而不是传统的HTML标签,所以属性是在服务器上处理的。不幸的是,这意味着内联脚本标签并不总是按照您的意愿行事。

你可以做几件事。要么不要runat="server"像你说的那样,让它完全按照你想要的方式呈现,要么在代码中设置值:

myTextBox.Value = "whatever";

您也可以使用数据绑定,但它有点难看:

<input id="myTextBox" runat="server" type="text"
    value='<%# HttpUtility.HtmlEncode("someString") %>' />

protected void Page_Load(object sender, EventArgs e) {
    myTextBox.DataBind();
}
于 2013-07-05T18:45:59.653 回答