用于检查复选框值的代码块
本文关键字:代码 检查 复选框 用于 | 更新日期: 2023-09-27 18:35:16
我是ASP和C#的新手,需要一些关于ASPX内部C#代码块的建议。我尝试根据复选框值更改标签文本。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page Language="C#" %>
<html>
<body>
<form id="form1" runat="server">
<asp:CheckBox runat="server" id="CheckBox1" AutoPostBack="True" Checked="True"></asp:CheckBox>
<% if (CheckBox1.Checked==True) {%>
<asp:Label id="Label1" runat="server" Text="Checked"></asp:Label>
<% } else {%>
<asp:Label id="Label1" runat="server" Text="Not Checked"></asp:Label>
<% }%>
</form>
</body>
</html>
它不起作用,我不确定这是否是正确的方法。
最好将标记和代码分成2个不同的文件(例如Default.aspx和Default.aspx.cs)。要更改标签文本,请尝试处理页面的加载事件。
默认值.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form id="form1" runat="server">
<asp:CheckBox runat="server" id="CheckBox1" AutoPostBack="True" Checked="True"></asp:CheckBox>
<asp:Label id="Label1" runat="server"></asp:Label>
</form>
</body>
</html>
默认值.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Label1.Text = CheckBox1.Checked ? "Checked" : "Not checked";
}
}
这是因为 true 仅拼写为小写。
您的代码工作正常,我假设您没有使用 IDE,因为它会告诉您未定义True
。 您必须将其更改为true
<% if (CheckBox1.Checked==true) {%>
首先,您必须使用javascript或jquery。 由于ASPX是一种服务器端语言,一旦加载,它将无法控制网页。