asp.net web中一個頁面去呼叫執行另一個頁面
阿新 • • 發佈:2020-10-29
文章: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頁面作為一個模板使用;這樣就不用拼模板了;