ASP.NET MVC4 の Web API を学んでみる その3 〜モデルを利用したバインド〜
前回は基本的なパラメータのバインディングを試したが、次にモデルを利用したバインディングを紹介する。
モデルを利用したバインドのサンプルコード
モデルクラス、Web API コントローラ、画面のソースコードを以下に記載する。
- HomeViewModel.cs
namespace Mvc4WebApiApp.ViewModels { public class HomeViewModel { public string Comment { get; set; } public int Hentai { get; set; } } }
ApiController も特に解説は不要だと思うが、DataContractJsonSerializer を利用してモデルを JSON 文字列に変換している点だけご注意いただきたい。
- VMValuesController.cs
using System.Collections.Generic; using System.Web.Http; using System.Diagnostics; using System.Runtime.Serialization.Json; using System.IO; using System.Text; using Mvc4WebApiApp.ViewModels; namespace Mvc4WebApiApp.Controllers { public class VMValuesController : ApiController { // GET /api/<controller> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET /api/<controller>/5 public string Get(int id) { return "value"; } // POST /api/<controller> public HomeViewModel Post(HomeViewModel model) { //DataContractJsonSerializer を利用したモデルのシリアライズ var ms = new MemoryStream(); new DataContractJsonSerializer(model.GetType()).WriteObject(ms, model); Debug.WriteLine("model = {1}", Encoding.UTF8.GetString(ms.ToArray())); return model; } // PUT /api/<controller>/5 public void Put(int id, string value) { } // DELETE /api/<controller>/5 public void Delete(int id) { } } }
- Index.cshtml
@model Mvc4WebApiApp.ViewModels.HomeViewModel
@{
ViewBag.Title = "ViewModel";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ASP.NET Web API</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div id="body">
<form id="myform" action="/">
<input type="button" id="api_button" value="リクエスト送付" />
<p>
<input type="radio" name="hentai" value="0" checked />とても変態
<input type="radio" name="hentai" value="1" />普通に変態
<input type="radio" name="hentai" value="2" />ちょっと変態
<input type="radio" name="hentai" value="3" />割と普通
</p>
<p>
<input type="text" value="文字列" name="comment" />
</p>
</form>
</div>
<script type="text/javascript">
$('#api_button').on('click', function () {
var data = $('#myform').serialize();
$.ajax({
type: 'POST',
url: '@Url.Content("~/api/vmvalues")',
data: data,
success: function (res) {
alert("response = "+JSON.stringify(res));
},
error: function (res) {
alert('エラー');
}
});
});
</script>
</body>
</html>
