C# 将属性添加到正文失败
我有一个asp.net网页。守则:C# 将属性添加到正文失败,c#,asp.net,html,C#,Asp.net,Html,我有一个asp.net网页。守则: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Works.Login" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Works.Login" %>
<!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 runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="/styles/source/style.css" />
</head>
<body id="PageBody" runat="server">
<form id="form1" runat="server">
<div style="text-align: center" >
但是我发现它根本不起作用。我进入代码,发现有一个异常
InnerText='((System.Web.UI.HtmlControl.HtmlContainerControl)((System.Web.UI.HtmlControl.HtmlGenericControl)(PageBody)))。InnerText'
引发了“System.Web.HttpException”类型的异常}
谢谢你的帮助。这对我很有用:
PageBody.Attributes["class"] = "some_image";
在PageLoad中执行此操作,它会工作
protected void Page_Load(object sender, EventArgs e)
{
if (PageBody != null)
{
PageBody.Attributes.Add("class", "myClass");
}
}
编辑:完整代码显示此功能正在工作(因为op可能已满)
我的ASPX页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="SO.WebForm4" %>
<!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 runat="server">
<title></title>
<style>
body
{
background-color:Olive;
}
.myClass
{
background-color:Orange;
}
</style>
</head>
<body id="PageBody" runat="server">
<form id="form1" runat="server">
<div>
<h2>Testing styles</h2>
<p>If the bg color is Orange, code is working</p>
</div>
</form>
</body>
</html>
这是输出
异常消息是什么?InnerText引发了“System.Web.HttpException”类型的异常。否,异常仍然存在。我测试过了。也请看@Love:是母版页吗?那么你应该在queston中提到。如果这是一个正常的页面,它会工作的。我测试过了,不管是大师级还是普通级,他们都是一样的,我在普通页面上测试过,但没有运气。你能在你的机器上测试一下吗?我使用asp.net 3.5。您是否已进入代码查看PageBody.InnerText?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="SO.WebForm4" %>
<!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 runat="server">
<title></title>
<style>
body
{
background-color:Olive;
}
.myClass
{
background-color:Orange;
}
</style>
</head>
<body id="PageBody" runat="server">
<form id="form1" runat="server">
<div>
<h2>Testing styles</h2>
<p>If the bg color is Orange, code is working</p>
</div>
</form>
</body>
</html>
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SO
{
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PageBody != null)
{
PageBody.Attributes.Add("class", "myClass");
}
}
}
}