简体   繁体   中英

Code blocks for checking checkbox value

I'm new to ASP and C# and need some advice on C# code blocks inside ASPX. I have tried changing label text depend on checkbox value.

<!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>

It is not working and i not sure if this is right way of doing this.

This is because true is spelled with lowercase only.
your code works fine, im assuming you are not using an IDE because it would have told you that True is not defined. you have to change it to true

<% if (CheckBox1.Checked==true)   {%> 

It would be better to separate your markup and code into 2 different files (eg Default.aspx & Default.aspx.cs ). To change label text try to handle page's load event.

Default.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>

Default.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";
    }
}

首先,由于aspx是服务器端语言,因此您必须使用javascript或jquery。一旦加载,aspx将无法控制网页。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM