Create and use a Web API
Last night, I taught a netizen to create a Web API in ASP. NET MVC and apply this API in the MVC view.
You can create a program model in ASP. net mvc:
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
After the model is created, you can start to create a Web API:
If your environment is the first time you create a Web API, it will open a text to teach you how to configure Global. asax. cs:
Note that the api route registration should be placed before the mvc route.
Next, write a method or function for your api:
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 (. contains (w. month) w. season = "Spring"; var B = new int [] {4, 5, 6}; if (B. contains (w. month) w. season = "Summer"; IEnumerable <int> c = new List <int> () {7, 8, 9}; if (c. contains (w. month) w. season = "Autumn"; var d = "10, 11, 12 ". split (new char [] {','}). select (I => Int32.Parse (I )). toArray (); if (d. contains (w. month) w. season = "Winter"; return w ;}}}Source Code
The above content is the construction of Web APIs. You can use the front-end interfaces.
Add a view on the ASP. net mvc website and add some html:
Add the click event for the button. That is, use jQuery ajax to POST the month entered by the user, and then the system returns the quarter:
$ (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) {region ('.label'}.html ("the month you entered: "+ response. month + "; the conversion quarter is:" + response. season + ". ") ;}, Failure: function (response) {alert (response. responseText) ;}, error: function (response) {alert (response. responseText );}});});});Source Code
Demo: