asp.net web中一个页面去调用执行另一个页面
HttpServerUtility.Execute 方法
HttpServerUtility.Execute 方法是个很有用的方法,可以直接执行一个aspx页,然后返回一个字符串,当然也可以执行用户控件;
文章:Asp.Net Server.Execute、Server.Transfer报“执行子请求时出错”解决方案
示例代码:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TestWebpageExec { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { StringWriter sw = new StringWriter(); HttpContext.Current.Server.Execute("/WebForm2.aspx", sw,false); string resultStr = sw.ToString(); int a = 0; } } }
resultStr就是执行另一个页面返回的字符串;
另一个页面的代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestWebpageExec.WebForm2" %> <table> <tr> <td>名字</td> <td>年龄</td> </tr> <% if (ListStudent != null && ListStudent.Count > 0) { foreach (var stu in ListStudent) { %> <tr> <td><%=stu.Name %></td> <td><%=stu.Age%></td> </tr> <% } } %> </table>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TestWebpageExec { public partial class WebForm2 : System.Web.UI.Page { public List<Student> ListStudent = new List<Student>(); protected void Page_Load(object sender, EventArgs e) { ListStudent.Add(new Student() { Age=11,Name="tom" }); ListStudent.Add(new Student() { Age = 12, Name = "xiao" }); ListStudent.Add(new Student() { Age = 13, Name = "long" }); ListStudent.Add(new Student() { Age = 10, Name = "yang" }); ListStudent.Add(new Student() { Age = 9, Name = "hui" }); } } public class Student { public string Name { get; set; } public int Age { get; set; } } }
可以把WebForm2 .aspx页面作为一个模板使用;这样就不用拼模板了;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2019-10-29 每个程序员都应该知道延迟数—Latency Numbers Every Programmer Should Know
2019-10-29 思考——如何设计高性能,高并发,高可用的系统
2019-10-29 ffmpeg常用命令-学习