UserList1クリック
jQuery

【jQuery】WCFサービス経由でjqGridに表示する方法

WCFで作ったサービスをajaxで呼び、jqGridに表示する方法メモ。
ScriptManagerは使わず、jQuery, jqGridのJSとCSSを読み込んで実行します。
今回はEntity Frameworkを使用して、ユーザ情報を取得するサンプルを作ります。

サンプルのパターンは↓の3つ

  • .NetのSystem.Collections.Generic.Listでそのまま返す
  • JSON文字列をセットしたMessageとして返す
  • JSON文字列で返す

サンプルソース

サービス側

まずサービス側です。
プロジェクトを右クリック ⇒ 追加 ⇒ 新しい項目 ⇒ Web ⇒ WCF サービス で追加。
インターフェースと実装クラスが作成されるはずです。
特別なことはしていないのでサクっと書きます。

IUser.cs, User.svc.cs


[ServiceContract]
public interface IUser
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    List<USER_ACCOUNT> UserList1();

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    Message UserList2();

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    string UserList3();
}


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class User : IUser
{
    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();

    /// <summary>
    /// .NetのListのまま返します。
    /// </summary>
    /// <returns></returns>
    List<USER_ACCOUNT> IUser.UserList1()
    {
        using (ASTRAEntities context = new ASTRAEntities())
        {
            List<USER_ACCOUNT> users = context.USER_ACCOUNT.ToList();
            return users;
        }
    }

    /// <summary>
    /// JSON文字列をセットしてMessage型で返します。
    /// </summary>
    /// <returns></returns>
    Message IUser.UserList2()
    {
        using (ASTRAEntities context = new ASTRAEntities())
        {
            List<USER_ACCOUNT> users = context.USER_ACCOUNT.ToList();
            string json = jsSerializer.Serialize(users);
            return WebOperationContext.Current.CreateTextResponse(json, "application/json; charset=utf-8", System.Text.Encoding.UTF8);
        }
    }

    /// <summary>
    /// JSON文字列で返します。
    /// </summary>
    /// <returns></returns>
    string IUser.UserList3()
    {
        using (ASTRAEntities context = new ASTRAEntities())
        {
            List<USER_ACCOUNT> users = context.USER_ACCOUNT.ToList();
            return jsSerializer.Serialize(users);
        }
    }
}

ちなみに「マークアップの表示」からのコードの編集は不要です。

Web.config

次にWeb.config。特別な記述は要りませんが、通常のサービス追加と同様に定義を追加してください。


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    :
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBehaviour" name="JQGrid.Services.User">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
          contract="JQGrid.Services.IUser" />
      </service>
      :
  </system.serviceModel>
</configuration>

HTML側

次にHTML。
プロジェクトを右クリック ⇒ 追加 ⇒ 新しい項目 ⇒ Web ⇒ HTMLページ で追加。

JqGridExample.html


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JqGridExample</title>
    <meta charset="utf-8" />
    <!-- キャッシュ制御 -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <meta http-equiv="Expires" content="0" />

    <link rel="stylesheet" type="text/css" href="css/libs/jquery-ui-1.12.1.custom/jquery-ui.min.css" />
    <link rel="stylesheet" type="text/css" href="css/libs/ui.jqgrid.min.css" />
    <link rel="stylesheet" type="text/css" href="css/libs/layout-default.min.css" />
    <script type="text/javascript" src="js/libs/jquery-ui-1.12.1.custom/jquery.min.js"></script>
    <script type="text/javascript" src="js/libs/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
    <script type="text/javascript" src="js/libs/grid.locale-ja.js"></script>
    <script type="text/javascript" src="js/libs/jquery.jqgrid.min.js"></script>
    <script>

        /**
         * ロード時は空のテーブルを表示する
         */
        $(document).ready(function () {

            // 空のGridを表示する
            setGridData();

            // ボタンクリック時の処理
            $('#btnUserList1').click(function () {
                $.ajax({
                    url: "Services/User.svc/UserList1",
                    type: 'GET',
                    cache: false,
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (o) {
                        //勝手にJavaScriptのオブジェクトに変換されるので、
                        //.Netのリストをそのまま使える
                        setGridData(o, this.url);
                    }
                });
            });

            $('#btnUserList2').click(function () {
                $.ajax({
                    url: "Services/User.svc/UserList2",
                    type: 'GET',
                    cache: false,
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (o) {
                        //そのまま使える
                        setGridData(o, this.url);
                    }
                });
            });

            $('#btnUserList3').click(function () {
                $.ajax({
                    url: "Services/User.svc/UserList3",
                    type: 'GET',
                    cache: false,
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (o) {
                        //文字列⇒JSONへパース
                        setGridData(JSON.parse(o), this.url);
                    }
                });
            });

            // クリア
            $('#btnClearGrid').click(function () {
                setGridData();
            });
        });

        /**
         * Gridにデータを設定する。
         */
        function setGridData(data, url) {

            // Gridオブジェクト初期化
            $("#gridUser").GridUnload();

            // 表示設定
            $("#gridUser").jqGrid({
                data: data
                , dataType: 'local'
                , colNames: ['ID', '名前', 'パスワード']
                , colModel: [
                    { id: 'ACCOUNT_ID', name: 'ACCOUNT_ID', width: '120px' }
                    , { id: 'ACCOUNT_NAME', name: 'ACCOUNT_NAME', width: '150px' }
                    , { id: 'ACCOUNT_PW', name: 'ACCOUNT_PW', width: '150px' }
                ]
                , height: '200px'
                , caption: 'ユーザ一覧[' + url + ']'
            });
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="button" id="btnUserList1" value="UserList1" /><input type="button" id="btnUserList2" value="UserList2" /><input type="button" id="btnUserList3" value="btnUserList3" /> <input type="button" id="btnClearGrid" value="クリア" />
        </div>
        <table id="gridUser" />
    </form>
</body>
</html>

※jqGridのdataTypeは’local’としています。
実行したらこんなイメージになります↓

初期表示
初期表示
UserList1クリック
UserList1クリック
UserList2クリック
UserList2クリック
UserList3クリック
UserList3クリック

以上、WCFサービスで取得したデータをjqGridに表示するサンプルでした。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です