ASP.NET で PageMethods を利用する手順 (ページメソッド)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<form id="form1" runat="server">
<asp:ScriptManager ID="scmMain" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div class="row">
<div class="span6">
<h2>PageMethod無し</h2>
<p>普通にポストバックします。</p>
<asp:Button ID="btnNoPageMethods" runat="server" Text="PageMethods無し" CssClass="btn-primary btn-large" OnClick="btnNoPageMethods_Click"/>
</div>
<div class="span6">
<h2>PageMethodあり</h2>
<p>内部でPageMethodsを利用して非同期にやりとりします。</p>
<asp:Button ID="btnWithPageMethods" runat="server" Text="PageMethodsあり" CssClass="btn-primary btn-large" OnClientClick="getData(); return false;"/>
</div>
</div>
<div class="row">
<div class="span6">
<asp:TextBox ID="txtNoPageMethods" runat="server"></asp:TextBox>
</div>
<div class="span6">
<asp:TextBox ID="txtWithPageMethods" runat="server"></asp:TextBox>
</div>
</div>
</form>
</div>
<script src="Scripts/jquery-1.9.0.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script>
function getData() {
PageMethods.GetData(onSuccess, onError);
}
function onSuccess(result, userContext, methodName) {
$('#txtWithPageMethods').val(result);
}
function onError(results, currentContext, methodName) {
alert('[Error] ' + results);
$('#txtWithPageMethods').val('');
}
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.UI;
namespace WebApplication1
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtNoPageMethods.Text = string.Empty;
txtWithPageMethods.Text = string.Empty;
}
}
protected void btnNoPageMethods_Click(object sender, EventArgs e)
{
txtNoPageMethods.Text = Default.GetData();
}
[WebMethod]
public static string GetData()
{
return DateTime.Now.ToLongTimeString();
}
}
}