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