5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASP.NET WebForm jQueryでPageのメソッドを呼び出す

Last updated at Posted at 2014-04-01

jQueryのajax等で、サーバーサイドの処理を呼び出したい!という場合以下のようにする。

サーバー側(AjaxTest.aspx.vb/AjaxTest.aspx.cs)

<WebMethod()>
Public Shared Function Echo(ByVal text As String) As String
    Return text
End Function
[WebMethod()]
public static string Echo(string text)
{
	return text;
}

JavaScript側

$.ajax({
    type: "POST",
    url:  "AjaxTest.aspx/Echo",
    data: JSON.stringify({ text: "echostring" }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache:false
}).done(function (data) {
    //data.dに返り値が入っている
})

注意すべきポイント

  • サーバーサイドのメソッドは、Shared(static)である必要がある。
  • 送るデータは、jsonでなく"文字列"である必要があるため、JSON.stringifyが必要(dataTypeでjsonを指定しているのに?不思議だがこれが真実)。
  • contentTypeの指定は必須(jQueryのデフォルトではapplication/x-www-form-urlencoded; charset=UTF-8のため、指定しないと失敗する。このため、$.postなどで横着すると失敗する)。
  • dataTypeも必要
  • cache:falseは必須ではないが、IEでおかしな挙動があったりするので基本あったほうがいいと思う。
  • 返り値は頼まなくてもJSONでシリアライズされてくるため、サーバーサイドでのJavaScriptSerializerによるシリアライズは不要

<誤情報>

  • よく言われる、web.configへのwebServicesセクションへの追加は不要
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>
  • ScriptManagerは必要なく、EnablePageMethods="true"も不要
  • メソッドにScriptMethodAttributeを付与する必要もない
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?