Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active December 11, 2015 17:08
Show Gist options
  • Save devlights/4631959 to your computer and use it in GitHub Desktop.
Save devlights/4631959 to your computer and use it in GitHub Desktop.
ASP.NET で PageMethods を利用する手順 (ページメソッド)
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();
}
}
}

手順

  • 画面にScriptManagerを配置
  • ScriptManagerのEnablePageMethodsプロパティにtrueを設定
  • コードビハインド側にWebMethod属性を付与したstaticなメソッドを定義
  • ビュー側にてPageMethodsを呼び出すjavascript関数を定義
    • PageMethodsを呼び出す際に成功時のコールバックとエラー時のコールバックを指定しておく
  • 結果を受け取り、反映する。(ここでjQueryを利用したりして処理すると楽)
<%@ 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment