LoginSignup
0
0

More than 5 years have passed since last update.

PageMethodsの結果がHTMLになる事象

Last updated at Posted at 2017-03-02

はまったのでメモ
※2017/9/6追記しました

事象

PageMethodsの呼び出し方はあっているはずなのに、
JavaScriptからPageMethodsの呼び出しを行うと結果値がHTMLになってしまう

正しくは、PageMethodsの結果がHTMLになっているわけではなく、
PageMethods自体が呼び出せていない
HTMLが返却されるのはASP.NET Friendly URLsによるもの

環境

  • Visual Studio 2015
  • ASP.NET Web Application(.NET Framework)のテンプレートで生成したプロジェクトを利用

原因

ASP.NET Friendly URLsを使用すると通常の方法でPageMethodsが呼び出せなくなる
Friendly URLsはASP.NETのテンプレートに含まれているので既定で使用状態となっている

Friendly URLsとは何か
http://aspnetfriendlyurls.codeplex.com/

具体的にはApp_Startの中にある RouteConfig.cs のコード

C#
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }

原因詳細

Default.aspxにあるTestMethodというPageMethodsを呼び出す場合、
Default.aspx/TestMethodにアクセスする必要があるが、
ASP.NET Friendly URLsを使用していると
Default/TestMethodにアクセスされたことになり
DefaultのHTMLが返却される

解決方法(Friendly URLsを使わない場合)

上記の原因コード(RegisterRoutes)をまるっと削除すれば完了

解決方法(Friendly URLsを使う場合)

PageMethodsを使う前に下記のコードを実行する

JavaScript
PageMethods.set_path(PageMethods.get_path() + '.aspx');

ただ実用するにはMasterページなどに下記のコードを入れたほうがいい

JavaScript
<script type="text/javascript">
    $(document).ready(function () {
        if ("PageMethods" in window) {
            if (PageMethods.get_path().slice(-5) != '.aspx') {
                PageMethods.set_path(PageMethods.get_path() + '.aspx');
            }
        }
    });
</script>

この状態でPageMethodsを呼び出すと、
コンソールに下記のエラーが出て実行出来ないかもしれない

Failed to load resource: the server responded with a status of 401 (Unauthorized)

上記のエラーを解消するにはRedirectMode.PermanentからRedirectMode.Offに変更するのが簡単

C#
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Off;  //This one!
        routes.EnableFriendlyUrls(settings);
    }

その他の設定変更でも対応可能かもしれませんが調べていないです。

500エラーが返される場合

C#側ページメソッドの引数をstringにしていて、
JS側ページメソッドのパラメータにJavaScriptのオブジェクト(配列など)を入れた場合
500エラーが返される

JavaScriptのオブジェクトを渡す場合はJSON文字列にする必要がある
オブジェクトを送りつけたい場合は、JSON.stringify()を使ってJSON文字列に変換するとよい

なお単純な文字列を渡したい場合は500エラーは発生しない

0
0
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
0
0