昨晚有教一個網友在ASP.NET MVC里,創建Web API和在MVC視圖中應用此API。 可以在ASP.NET MVC中,創建程式的model: namespace Insus.NET.Models { public class Weather { private int _Month; pub ...
昨晚有教一個網友在ASP.NET MVC里,創建Web API和在MVC視圖中應用此API。
namespace Insus.NET.Models { public class Weather { private int _Month; public int Month { get { return _Month; } set { _Month = value; } } private string _Season; public string Season { get { return _Season; } set { _Season = value; } } } }Source Code
如果你的環境是第一次創建Web API的,它會打開一個文本,是教訴你怎樣配置Global.asax.cs的:
namespace Insus.NET.Apis { public class WeatherAPIController : ApiController { [Route("api/WeatherAPI/ApiMethod")] [HttpPost] public Weather ApiMethod(Weather w) { var a = new List<int>() { 1, 2, 3 }; if (a.Contains(w.Month)) w.Season = "春季"; var b = new int[] { 4, 5, 6 }; if (b.Contains(w.Month)) w.Season = "夏季"; IEnumerable<int> c = new List<int>() { 7, 8, 9 }; if (c.Contains(w.Month)) w.Season = "秋季"; var d = "10,11,12".Split(new char[] { ',' }).Select(i => Int32.Parse(i)).ToArray(); if (d.Contains(w.Month)) w.Season = "冬季"; return w; } } }Source Code
以上內容全是Web API的建設。前端介面,就可以使用它們了。
現在ASP.NET MVC網站上,添加一個視圖,並添加一些html:
為銨鈕補充click事件,那是使用jQuery的ajax來POST用戶輸入的月份,然後系統返回季度:
$(function () { $("#btnConvert").click(function () { var obj = {}; obj.Month = $("#txtMonth").val(); $.ajax({ type: "POST", url: "/api/WeatherAPI/ApiMethod", data: JSON.stringify(obj), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $('.label').html("你輸入的月份:" + response.Month + "; 轉換季度是:" + response.Season + "。"); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); }); });Source Code
演示: