ASP.NET MVC 4 Web API + jQuery HttpRequest – Restful Web Services ( JSON ) : POST 方法
Web API Controller |
using Newtonsoft.Json.Linq; public class PlayerController : ApiController { private JArray ary = new JArray(); public PlayerController() { JObject obj; obj = new JObject(); obj.Add("PlayerID", 1); obj.Add("PlayerName", "Player 1"); ary.Add(obj); obj = new JObject(); obj.Add("PlayerID", 2); obj.Add("PlayerName", "Player 2"); ary.Add(obj); obj = new JObject(); obj.Add("PlayerID", 3); obj.Add("PlayerName", "Player 3"); ary.Add(obj); obj = new JObject(); obj.Add("PlayerID", 4); obj.Add("PlayerName", "Player 4"); ary.Add(obj); obj = new JObject(); obj.Add("PlayerID", 5); obj.Add("PlayerName", "Player 5"); ary.Add(obj); } … … public JObject Post(JObject obj) { foreach(JObject item in ary) { if (Int32.Parse(item["PlayerID"].ToString()) == Int32.Parse(obj["id"].ToString())) { return item; } } return null; } … … } |
View ( jQuery ) |
@section Scripts { < script type="text/javascript" > $(document).ready(function () { $("#btn").click(function () { para = { "id": $("#PlayerID").val() }; $.ajax({ url: "/api/player", type: "POST", data: para, success: function (data) { $("#result").html(JSON.stringify(data)); } }); }); }); < /script > } < input id="PlayerID" type="text" value="" /> < div id="btn" style="cursor:pointer;" >Button< /div > < div id="result" >< /div > |