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页面作为一个模板使用;这样就不用拼模板了;

 

 

 

 

 

 

 

 

posted on   荆棘人  阅读(637)  评论(0编辑  收藏  举报

编辑推荐:
· 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常用命令-学习

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示