ASP.NET MVCとknockout.jsの連携:引数を渡してJSONを取得
2012/04/16
「http://xxxx.xx/Home/Js009/」をブラウザに入力したら「$.getJSON()」が実行。
その際に「Js009」を引数としたい。
その際に「Js009」を引数としたい。
ソース
コントローラー:Controllers/HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace TestProject.Controllers
- {
- public class JqueryController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult Js009()
- {
- return View();
- }
- public ActionResult TestDataOfJsonWithArgument(string arg)
- {
- List<Dictionary<string, string>> list = new List<Dictionary<string, string>>()
- {
- new Dictionary<string, string>() { {"id", "1"}, {"item", "ねぎ間"}, {"price", "168"} },
- new Dictionary<string, string>() { {"id", "2"}, {"item", "ハツ"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "3"}, {"item", "レバー"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "4"}, {"item", "ぼんちり"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "5"}, {"item", "はらみ"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "6"}, {"item", "うずら玉子"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "7"}, {"item", "なんこつ"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "8"}, {"item", "手羽先"}, {"price", "168"} },
- new Dictionary<string, string>() { {"id", "9"}, {"item", "せせり"}, {"price", "136"} },
- new Dictionary<string, string>() { {"id", "10"}, {"item", "白レバー"}, {"price", "168"} },
- new Dictionary<string, string>() { {"id", "11"}, {"item", "丸ごとシマウマ"}, {"price", "290"} },
- };
- return Json(list, JsonRequestBehavior.AllowGet);
- }
- }
- }
※引数として「arg」を受け取っているけど処理は何もしていない。
ビュー:Views/Home/Js009.cshtml
- @{
- ViewBag.Title = "「action」を引数にしてJSON取得";
- string JsonArg = this.ViewContext.Controller.ControllerContext.RouteData.Values["action"] as string;
- }
- <script type="text/javascript">
- $(document).ready(function () {
- // ko.applyBindingsで実行される中身?
- function viewModel() {
- var self = this;
- // ko.observable()で初期化?
- self.items = ko.observable();
- // $.getJSONでデータの読込み
- $.getJSON('@Url.Action("TestDataOfJsonWithArgument")', { arg: "@JsonArg" }, self.items);
- }
- // ドキュメントが読み込まれたらko.applyBindings()を実行
- ko.applyBindings(new viewModel());
- });
- </script>
- <h2>@ViewBag.Title</h2>
- <table>
- <thead>
- <tr>
- <th>id</th>
- <th>item</th>
- <th>price</th>
- </thead>
- <tbody data−bind="foreach: items">
- <tr>
- <td data−bind="text: id"></td>
- <td data−bind="text: item"></td>
- <td data−bind="text: price+' 円'"></td>
- </tr>
- </tbody>
- </table>
めも
コントローラー側の「TestDataOfJsonWithArgument(string arg)」(21行目)の「arg」と、ビュー側の「{ arg: "@JsonArg" }」(16行目)の「arg」は合わせる必要あり。
ビュー側の「string JsonArg = this.ViewContext.Controller.ControllerContext.RouteData.Values["action"] as string;」(3行目)で設定した「JsonArg」をscriptタグ内で使うので「@JsonArg」とする。文字列だから「"」でくくる必要もある。