18
21

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 MVCでWebAPIテンプレートを使わずJSONを返す

Posted at

背景

普通のMVCでさらっとJSONを返したいときのメモ。
C#というかASP.NETでJSON返すのはいちいちクラスとか定義しないといけなくてしんどい。

素のJSONを返す

文字列でJSONをそのまま返す例。""で囲まないと動かない。''ではだめ。

public ActionResult json01()
{
    //素のテキスト('ではだめみたい)
    string json = "{\"status\":\"OK\"}";

    //return
    return Content(json,"application/json");
}

結果は下記の通り。

{"status":"OK"}

ちょっとしたJSONを返す

私がよくつかうJSONフォーマットを返す例。
objectとそのList<>を使う。

public ActionResult json02()
{
    //list data
    List<object> objList = new List<object>();
    objList.Add(new { id=1,name="hoge"});
    objList.Add(new { id = 2, name = "foo" });

    //response
    object obj = new { status = "OK",data = objList};

    //return
    return Json(obj, JsonRequestBehavior.AllowGet);

}

結果は下記の通り。

{"status":"OK","data":[{"id":1,"name":"hoge"},{"id":2,"name":"foo"}]}

APIを呼び出す側のHTML

呼び出す側のHTML(というかView)の例。
標準で指定される_Layout.chtmlは、bodyの下の方で下記のようにjQueryが読み込まれており、その後に出現する@RenderSection()を利用して記述します。

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

実際にchtml側では下記のように記述します。


<h2>テストページ</h2>

<button id="btn">JSONを取得</button>

@section scripts{
    <script>
        $(function () {

            $("#btn").click(function () {
                $.getJSON("/Home/json01", null, function (json) {
                    alert(json.status);
                });
            });
        });
    </script>
}
18
21
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
18
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?