LoginSignup
27
27

More than 5 years have passed since last update.

初心者のための「ASP.NET Web Forms」でJsonを返すサンプル。

Last updated at Posted at 2013-06-03

2014/04/19
ここを読んでみて、この記事が誤解を与えそうだったので、文章を修正しました。


ASP.NETのJsonを返すサンプルをググっても、「ASP.NET MVC」だったりして「ASP.NET Web Form」のJsonを扱うサンプルを見つけることがなかなか難しかったりします。(見つかったとしても、ASP.NETの初心者には難しすぎたりと....)

まぁ、というわけで「ASP.NET Web Form」のすごくシンプルなサンプルを以下に示しておきます。

  • TestJson.aspx
    Json形式のデータを取得するため、Json形式のデータをResponse.Output.Writeするためだけのページです。
    基本的に他のページから参照されるだけで、このページが直接参照されることはないです。

  • TestJson.aspx.cs
    TestJson.aspxのコードですね。匿名型のオブジェクトをJavaScriptSerializerで文字列に変換しResponse.Output.Writeしています。

  • Output.aspx
    TestJson.aspxからJson形式のデータを取得して、実際にそのデータを表示するページです。
    今回のサンプルでは、jQueryのajaxメソッドを使用して取得しています。
    ajaxメソッドの第一引数のメンバにdataType: 'json'を指定してあげると、urlで指定したページの内容をjson形式のデータだと認識してくれるのでありがたいですね。
    その結果はsuccess: function(data){ ... }のdataにオブジェクトとして格納されているので、data.hogeのようにJson形式のデータを簡単にアクセスできます。

これを実行するとhttp://localhost:9672/Output.aspxのようにしてアクセスできるページになります。

サンプル

Output.aspx

<!doctype html>

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Output.aspx.cs" Inherits="Output" %>

<html>
  <head>
    <script src="javascripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $('#json').on('mouseover', function(){
                var self = this;
                $.ajax({
                  url: 'TestJson.aspx',
                  type: "get",
                  dataType: 'json',
                  success: function(data){
                    $(self).html(data.hoge);
                  }
                });
              });
        });
    </script>
  </head>
  <body>
    <secsion>
      <div id="json">マウスオーバーするとここに出力します。</div>
    </secsion>
  </body>
</html>

TestJson.aspx.cs

using System;

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        dynamic dataSet = new { hoge = "foo" };
        var s = new System.Web.Script.Serialization.JavaScriptSerializer();
        Response.ContentType = "text/javascript";
        Response.Output.Write(s.Serialize(dataSet));
        Response.End();
    }
}

TestJson.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestJson.aspx.cs" Inherits="TestJson" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>
27
27
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
27
27