Customers.aspx
=AJAX, 向web service請求資料。
[script]
function displayCustomers(result) {
$get("customers").innerHTML = result;
}
[script]

[body]
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/CustomerService.asmx" />
</Services>
</asp:ScriptManager>

Enter Country: <input id="Country" type="text" />
<a href="javascript:CustomerService.GetCustomersByCountry($get('Country').value, displayCustomers)">Show Customers</a>
<div id="customers"></div>
[/body]

CustomerService.cs
=這個AJAX用的web service是宣告 System.Web.Script.Services.ScriptService
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class CustomerService : System.Web.Services.WebService {

[WebMethod]
public string GetCustomersByCountry(string country)
{
NorthwindTableAdapters.CustomersTableAdapter customersAdapter = new NorthwindTableAdapters.CustomersTableAdapter();
Northwind.CustomersDataTable customers = customersAdapter.GetCustomersByCountry(country);

if (customers.Rows.Count > 0)
return ViewManager.RenderView("~/App_Views/Customers.ascx", customers);
else
return ViewManager.RenderView("~/App_Views/NoCustomers.ascx", null);
}
}

Customers.ascx.cs
=View
using System;

public partial class App_Views_Customers : System.Web.UI.UserControl
{
public object Data;

protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = Data;
Repeater1.DataBind();
}
}

ViewManager.cs
=Controller
using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Reflection;

public class ViewManager
{
public static string RenderView(string path)
{
return RenderView(path, null);
}

public static string RenderView(string path, object data)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl) pageHolder.LoadControl(path);

if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");

if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("View file: " + path + " does not have a public Data property");
}
}

pageHolder.Controls.Add(viewControl);

StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);

return output.ToString();
}
}
 


ASP.NET 1.1 只能用在.aspx上
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute("~/ajax.aspx", output);
return output.ToString();

參考資料: