You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET中将aspx.cs的结果显示到指定HTML表格标签中

解决ASP.NET中相加结果显示到Table内的问题

你需要修改前端页面添加结果展示控件,并调整后端代码将结果赋值给该控件,具体步骤如下:

1. 修改前端ASPX页面

在现有的<table>中添加一行,用于展示计算结果,使用asp:Label控件(需设置runat="server"让后端能访问):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table id="tbl1" align="center">
                <tr>
                    <th>
                        Enter the Number1:
                        <asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
                    </th>
                </tr>
                <tr>
                    <th>
                        Enter the Number2:
                        <asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
                    </th>
                </tr>
                <tr>
                    <th>
                         <asp:Button ID="Button2" runat="server" Text="Add" OnClick="Button1_Click" />
                    </th>
                </tr>
                <!-- 添加结果展示行 -->
                <tr>
                    <th>
                        相加结果:
                        <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
                    </th>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

2. 修改后端aspx.cs代码

移除Response.Write(c),改为将计算结果赋值给刚才添加的lblResult控件,同时增加输入验证避免报错:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace sample1
{
    public partial class First: System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textbox1.Text, out int no1) && int.TryParse(textbox2.Text, out int no2))
            {
                int c = no1 + no2;
                lblResult.Text = c.ToString();
            }
            else
            {
                lblResult.Text = "请输入有效的整数";
            }
        }
    }
}

说明

  • 原来的Response.Write()会直接将内容输出到页面最顶部,无法控制展示位置;使用服务器端asp:Label控件可以精准把结果放在Table指定位置。
  • 添加int.TryParse验证是为了避免用户输入非数字内容时页面报错,提升页面健壮性。

内容的提问来源于stack exchange,提问作者Sudarshan Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:09:25