背景
普通の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>
}