Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API

In this article you will learn how to display the weather forecast in Asp.Net MVC using OpenWeatherMap Weather API.
 
Before starting and working on this article first visit the following site and register yourself and get an API key:
 
https://www.openweathermap.org/
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
Create project called “WeatherForecast”
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
Select MVC
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
Select the following things as per the image,
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
After pressing OK, Visual Studio creates the project WeatherForecast.
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
Now switch to HomeController and create new actionmethod called “Weather”.
  1.      public ActionResult Weather()  
  2.      {  
  3.   
  4.          return View();  
  5.      }  
Create a Weather view.
 
Right click on Weather action method ---> Add View
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API 
 
Switch to Weather.cshtml file add the following code,
  1. @{    
  2.     ViewBag.Title = "Weather";    
  3. }    
  4.     
  5. <h1>Search City and Get Weather Forecast</h1>    
  6.     
  7. <div>    
  8.     <strong>City Name  :</strong><input id="txtCity" type="text"/>    
  9.     <br />    
  10.     <br />    
  11.     <button id="btnSubmit">Get Weather Forecast</button>    
  12. </div>    
  13.     
  14.     
  15. <div>    
  16.     <h2>Weather Forecast</h2>    
  17.     <table>    
  18.         <tr>    
  19.             <td>Weather Symbol Icon <img id="imgWeatherIconUrl" src="" title="Weather Icon" /></td>    
  20.         </tr>    
  21.         <tr>    
  22.             <td>    
  23.                 <strong>City: </strong>    
  24.                 <span id="lblCity"></span>  ,    
  25.                 <span id="lblCountry"></span>    
  26.             </td>    
  27.             </tr>    
  28.         <tr>    
  29.             <td>    
  30.                 <strong>Latitude: </strong>    
  31.                 <label id="lblLat"></label><br />    
  32.                 <strong>Longitude: </strong>    
  33.                 <label id="lblLon"></label>    
  34.                     
  35.             </td>    
  36.         </tr>    
  37.         <tr>    
  38.             <td>    
  39.                 <strong>Description:</strong>    
  40.                 <label id="lblDescription"></label><br />    
  41.                 <strong>Humidity:</strong>    
  42.                 <label id="lblHumidity"></label>    
  43.             </td>    
  44.             </tr>    
  45.         <tr>    
  46.             <td>    
  47.                 Temperature (Feels Like)<label id="lblTempFeelsLike"></label><br />    
  48.                 Temperature <label id="lblTemp"></label><br />    
  49.                 Temperature (Min)<label id="lblTempMin"></label><br />    
  50.                 Temperature (Max)<label id="lblTempMax"></label><br />    
  51.             </td>    
  52.         </tr>    
  53.            
  54.     
  55.     </table>    
  56. </div>    
  57.     
  58. <script>    
  59.         
  60.     $("#btnSubmit").click(function () {    
  61.     
  62.         var cityname = $("#txtCity").val();    
  63.         if (cityname.length > 0)    
  64.         {    
  65.         $.ajax({    
  66.             url: "http://localhost:52189/Home/WeatherDetail?City="+cityname,    
  67.             type: "POST",    
  68.             success: function (rsltval) {    
  69.                 var data =JSON.parse(rsltval);    
  70.                 console.log(data);    
  71.                 $("#lblCity").html(data.City);    
  72.                 $("#lblCountry").text(data.Country);    
  73.                 $("#lblLat").text(data.Lat);    
  74.                 $("#lblLon").text(data.Lon);    
  75.                 $("#lblDescription").text(data.Description);    
  76.                 $("#lblHumidity").text(data.Humidity);    
  77.                 $("#lblTempFeelsLike").text(data.TempFeelsLike);    
  78.                 $("#lblTemp").text(data.Temp);    
  79.                 $("#lblTempMax").text(data.TempMax);    
  80.                 $("#lblTempMin").text(data.TempMin);    
  81.                 $("#imgWeatherIconUrl").attr("src""http://openweathermap.org/img/w/" + data.WeatherIcon + ".png");    
  82.                 //data - response from server    
  83.             },    
  84.             error: function () {    
  85.     
  86.             }    
  87.         });    
  88.         }    
  89.         else    
  90.         {    
  91.             alert("City Not Found");    
  92.         }    
  93.     });    
  94.     
  95. </script>    
OUTPUT of Weather.cshtml
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
Switch to Controller to create ActionMethod which we call from jQuery AJAX.
 
JSON received in response from API http://api.openweathermap.org/data/2.5/weather:
  1. {"coord":{"lon":72.85,"lat":19.01},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],"base":"stations","main":{"temp":31.75,"feels_like":31.51,"temp_min":31,"temp_max":32.22,"pressure":1014,"humidity":43},"visibility":2500,"wind":{"speed":4.1,"deg":140},"clouds":{"all":0},"dt":1578730750,"sys":{"type":1,"id":9052,"country":"IN","sunrise":1578707041,"sunset":1578746875},"timezone":19800,"id":1275339,"name":"Mumbai","cod":200}  
We created Class from JSON with the help of http://json2chsarp.com, and we need VIEWMODEL to send data from Controller to View. ViewModel helps us to send data and display data.
 
To Convert JSON to C# class : http://json2csharp.com/
 
We have to create CLASSES and VIEWMODEL in file called WeatherViewModel.cs.
 
Right click on MODELS folder, select ADD-->CLASS
 
WeatherViewModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace WeatherForecast.Models  
  7. {  
  8.     public class ResultViewModel  
  9.     {  
  10.         public string City { getset; }  
  11.         public string Country { getset; }  
  12.         public string Lat { getset; }  
  13.         public string Lon { getset; }  
  14.         public string Description { getset; }  
  15.         public string Humidity { getset; }  
  16.         public string TempFeelsLike { getset; }  
  17.         public string Temp{ getset; }  
  18.         public string TempMax { getset; }  
  19.         public string TempMin { getset; }  
  20.         public string WeatherIcon { getset; }  
  21.     }  
  22.   
  23.     public class Coord  
  24.     {  
  25.         public double lon { getset; }  
  26.         public double lat { getset; }  
  27.     }  
  28.   
  29.     public class Weather  
  30.     {  
  31.         public int id { getset; }  
  32.         public string main { getset; }  
  33.         public string description { getset; }  
  34.         public string icon { getset; }  
  35.     }  
  36.   
  37.     public class Main  
  38.     {  
  39.         public double temp { getset; }  
  40.         public double feels_like { getset; }  
  41.         public int temp_min { getset; }  
  42.         public double temp_max { getset; }  
  43.         public int pressure { getset; }  
  44.         public int humidity { getset; }  
  45.     }  
  46.   
  47.     public class Wind  
  48.     {  
  49.         public double speed { getset; }  
  50.         public int deg { getset; }  
  51.     }  
  52.     
  53.     public class Clouds  
  54.     {  
  55.         public int all { getset; }  
  56.     }  
  57.   
  58.     public class Sys  
  59.     {  
  60.         public int type { getset; }  
  61.         public int id { getset; }  
  62.         public string country { getset; }  
  63.         public int sunrise { getset; }  
  64.         public int sunset { getset; }  
  65.     }  
  66.   
  67.     public class RootObject  
  68.     {  
  69.         public Coord coord { getset; }  
  70.         public List<Weather> weather { getset; }  
  71.         public string @base { getset; }  
  72.         public Main main { getset; }  
  73.         public int visibility { getset; }  
  74.         public Wind wind { getset; }  
  75.         public Clouds clouds { getset; }  
  76.         public int dt { getset; }  
  77.         public Sys sys { getset; }  
  78.         public int timezone { getset; }  
  79.         public int id { getset; }  
  80.         public string name { getset; }  
  81.         public int cod { getset; }  
  82.     }  
  83. }  
Switch again to HomeController to write the method to fetch the response/data from OPENWEATHERMAP.ORG through the api.
 
Following NAMESPACES ADDED
  1. using System.Net;  
  2. using System.Web.Mvc;  
  3. using System.Web.Script.Serialization;  
  4. using WeatherForecast.Models;  
  5.   
  6.         [HttpPost]  
  7.         public  String WeatherDetail(string City)  
  8.         {  
  9.   
  10.             //Assign API KEY which received from OPENWEATHERMAP.ORG  
  11.             string appId = "8113fcc5a7494b0518bd91ef3acc074f";  
  12.   
  13.             //API path with CITY parameter and other parameters.  
  14.             string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&cnt=1&APPID={1}", City, appId);  
  15.   
  16.             using (WebClient client = new WebClient())  
  17.             {  
  18.                 string json = client.DownloadString(url);  
  19.                   
  20.                 //********************//  
  21.                 //     JSON RECIVED   
  22.                 //********************//  
  23.                 //{"coord":{ "lon":72.85,"lat":19.01},  
  24.                 //"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],  
  25.                 //"base":"stations",  
  26.                 //"main":{"temp":31.75,"feels_like":31.51,"temp_min":31,"temp_max":32.22,"pressure":1014,"humidity":43},  
  27.                 //"visibility":2500,  
  28.                 //"wind":{"speed":4.1,"deg":140},  
  29.                 //"clouds":{"all":0},  
  30.                 //"dt":1578730750,  
  31.                 //"sys":{"type":1,"id":9052,"country":"IN","sunrise":1578707041,"sunset":1578746875},  
  32.                 //"timezone":19800,  
  33.                 //"id":1275339,  
  34.                 //"name":"Mumbai",  
  35.                 //"cod":200}  
  36.   
  37.                 //Converting to OBJECT from JSON string.  
  38.                 RootObject weatherInfo = (new JavaScriptSerializer()).Deserialize<RootObject>(json);  
  39.   
  40.                 //Special VIEWMODEL design to send only required fields not all fields which received from   
  41.                 //www.openweathermap.org api  
  42.                 ResultViewModel rslt = new ResultViewModel();  
  43.   
  44.                 rslt.Country = weatherInfo.sys.country;  
  45.                 rslt.City = weatherInfo.name;  
  46.                 rslt.Lat = Convert.ToString(weatherInfo.coord.lat);  
  47.                 rslt.Lon = Convert.ToString(weatherInfo.coord.lon);  
  48.                 rslt.Description = weatherInfo.weather[0].description;  
  49.                 rslt.Humidity = Convert.ToString(weatherInfo.main.humidity);  
  50.                 rslt.Temp = Convert.ToString(weatherInfo.main.temp);  
  51.                 rslt.TempFeelsLike = Convert.ToString(weatherInfo.main.feels_like);  
  52.                 rslt.TempMax = Convert.ToString(weatherInfo.main.temp_max);  
  53.                 rslt.TempMin = Convert.ToString(weatherInfo.main.temp_min);  
  54.                 rslt.WeatherIcon = weatherInfo.weather[0].icon;  
  55.   
  56.                 //Converting OBJECT to JSON String   
  57.                 var jsonstring = new JavaScriptSerializer().Serialize(rslt);  
  58.   
  59.                 //Return JSON string.  
  60.                 return jsonstring;  
  61.             }  
  62.         }  
NOTE
Before running the project switch _layout.cshtml, which is located inside VIEWS--->SHARED folder.
 
Move the following two lines in the head section.
 
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
 
Now Press F5 to Execute the Project,
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 
After clicking on the GET WEATHER FORECAST button, you'll get the  following output.
 
OUTPUT
 
Display Weather Forecast In ASP.NET MVC Using OpenWeatherMap Weather API
 

Full Source Code

 
_Layout.cshtml code
  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <meta charset="utf-8" />    
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">    
  6.     <title>@ViewBag.Title - My ASP.NET Application</title>    
  7.     @Styles.Render("~/Content/css")    
  8.     @Scripts.Render("~/bundles/modernizr")    
  9.     @Scripts.Render("~/bundles/jquery")    
  10.     @Scripts.Render("~/bundles/bootstrap")    
  11. </head>    
  12. <body>    
  13.     <div class="navbar navbar-inverse navbar-fixed-top">    
  14.         <div class="container">    
  15.             <div class="navbar-header">    
  16.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">    
  17.                     <span class="icon-bar"></span>    
  18.                     <span class="icon-bar"></span>    
  19.                     <span class="icon-bar"></span>    
  20.                 </button>    
  21.                 @Html.ActionLink("Application name""Index""Home"new { area = "" }, new { @class = "navbar-brand" })    
  22.             </div>    
  23.             <div class="navbar-collapse collapse">    
  24.                 <ul class="nav navbar-nav">    
  25.                     <li>@Html.ActionLink("Home""Index""Home")</li>    
  26.                     <li>@Html.ActionLink("About""About""Home")</li>    
  27.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>    
  28.                 </ul>    
  29.             </div>    
  30.         </div>    
  31.     </div>    
  32.     <div class="container body-content">    
  33.         @RenderBody()    
  34.         <hr />    
  35.         <footer>    
  36.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>    
  37.         </footer>    
  38.     </div>    
  39.     
  40.      
  41.     @RenderSection("scripts", required: false)    
  42. </body>    
  43. </html>    
WeatherViewModel.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace WeatherForecast.Models  
  7. {  
  8.     public class ResultViewModel  
  9.     {  
  10.         public string City { getset; }  
  11.         public string Country { getset; }  
  12.         public string Lat { getset; }  
  13.         public string Lon { getset; }  
  14.         public string Description { getset; }  
  15.         public string Humidity { getset; }  
  16.         public string TempFeelsLike { getset; }  
  17.         public string Temp{ getset; }  
  18.         public string TempMax { getset; }  
  19.         public string TempMin { getset; }  
  20.         public string WeatherIcon { getset; }  
  21.     }  
  22.   
  23.     public class Coord  
  24.     {  
  25.         public double lon { getset; }  
  26.         public double lat { getset; }  
  27.     }  
  28.   
  29.     public class Weather  
  30.     {  
  31.         public int id { getset; }  
  32.         public string main { getset; }  
  33.         public string description { getset; }  
  34.         public string icon { getset; }  
  35.     }  
  36.   
  37.     public class Main  
  38.     {  
  39.         public double temp { getset; }  
  40.         public double feels_like { getset; }  
  41.         public int temp_min { getset; }  
  42.         public double temp_max { getset; }  
  43.         public int pressure { getset; }  
  44.         public int humidity { getset; }  
  45.     }  
  46.   
  47.     public class Wind  
  48.     {  
  49.         public double speed { getset; }  
  50.         public int deg { getset; }  
  51.     }  
  52.   
  53.     public class Clouds  
  54.     {  
  55.         public int all { getset; }  
  56.     }  
  57.   
  58.     public class Sys  
  59.     {  
  60.         public int type { getset; }  
  61.         public int id { getset; }  
  62.         public string country { getset; }  
  63.         public int sunrise { getset; }  
  64.         public int sunset { getset; }  
  65.     }  
  66.   
  67.     public class RootObject  
  68.     {  
  69.         public Coord coord { getset; }  
  70.         public List<Weather> weather { getset; }  
  71.         public string @base { getset; }  
  72.         public Main main { getset; }  
  73.         public int visibility { getset; }  
  74.         public Wind wind { getset; }  
  75.         public Clouds clouds { getset; }  
  76.         public int dt { getset; }  
  77.         public Sys sys { getset; }  
  78.         public int timezone { getset; }  
  79.         public int id { getset; }  
  80.         public string name { getset; }  
  81.         public int cod { getset; }  
  82.     }  
  83. }  
Weather.cshtml code
  1. @{    
  2.     ViewBag.Title = "Weather";    
  3. }    
  4.     
  5. <h1>Search City and Get Weather Forecast</h1>    
  6.     
  7. <div>    
  8.     <strong>City Name  :</strong><input id="txtCity" type="text"/>    
  9.     <br />    
  10.     <br />    
  11.     <button id="btnSubmit">Get Weather Forecast</button>    
  12. </div>    
  13.     
  14.     
  15. <div>    
  16.     <h2>Weather Forecast</h2>    
  17.     <table>    
  18.         <tr>    
  19.             <td>Weather Symbol Icon <img id="imgWeatherIconUrl" src="" title="Weather Icon" /></td>    
  20.         </tr>    
  21.         <tr>    
  22.             <td>    
  23.                 <strong>City: </strong>    
  24.                 <span id="lblCity"></span>  ,    
  25.                 <span id="lblCountry"></span>    
  26.             </td>    
  27.             </tr>    
  28.         <tr>    
  29.             <td>    
  30.                 <strong>Latitude: </strong>    
  31.                 <label id="lblLat"></label><br />    
  32.                 <strong>Longitude: </strong>    
  33.                 <label id="lblLon"></label>    
  34.                     
  35.             </td>    
  36.         </tr>    
  37.         <tr>    
  38.             <td>    
  39.                 <strong>Description:</strong>    
  40.                 <label id="lblDescription"></label><br />    
  41.                 <strong>Humidity:</strong>    
  42.                 <label id="lblHumidity"></label>    
  43.             </td>    
  44.             </tr>    
  45.         <tr>    
  46.             <td>    
  47.                 Temperature (Feels Like)<label id="lblTempFeelsLike"></label><br />    
  48.                 Temperature <label id="lblTemp"></label><br />    
  49.                 Temperature (Min)<label id="lblTempMin"></label><br />    
  50.                 Temperature (Max)<label id="lblTempMax"></label><br />    
  51.             </td>    
  52.         </tr>    
  53.            
  54.     
  55.     </table>    
  56. </div>    
  57.     
  58. <script>    
  59.         
  60.     $("#btnSubmit").click(function () {    
  61.     
  62.         var cityname = $("#txtCity").val();    
  63.         if (cityname.length > 0)    
  64.         {    
  65.         $.ajax({    
  66.             url: "http://localhost:52189/Home/WeatherDetail?City="+cityname,    
  67.             type: "POST",    
  68.             success: function (rsltval) {    
  69.                 var data =JSON.parse(rsltval);    
  70.                 console.log(data);    
  71.                 $("#lblCity").html(data.City);    
  72.                 $("#lblCountry").text(data.Country);    
  73.                 $("#lblLat").text(data.Lat);    
  74.                 $("#lblLon").text(data.Lon);    
  75.                 $("#lblDescription").text(data.Description);    
  76.                 $("#lblHumidity").text(data.Humidity);    
  77.                 $("#lblTempFeelsLike").text(data.TempFeelsLike);    
  78.                 $("#lblTemp").text(data.Temp);    
  79.                 $("#lblTempMax").text(data.TempMax);    
  80.                 $("#lblTempMin").text(data.TempMin);    
  81.                 $("#imgWeatherIconUrl").attr("src""http://openweathermap.org/img/w/" + data.WeatherIcon + ".png");    
  82.                 //data - response from server    
  83.             },    
  84.             error: function () {    
  85.     
  86.             }    
  87.         });    
  88.         }    
  89.         else    
  90.         {    
  91.             alert("City Not Found");    
  92.         }    
  93.     });    
  94.     
  95. </script>    
HomeController.cs code 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using System.Web.Script.Serialization;  
  8. using WeatherForecast.Models;  
  9.   
  10. namespace WeatherForecast.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.   
  15.         public ActionResult Weather()  
  16.         {  
  17.   
  18.             return View();  
  19.         }  
  20.   
  21.         public ActionResult Index()  
  22.         {  
  23.             return View();  
  24.         }  
  25.   
  26.         public ActionResult About()  
  27.         {  
  28.             ViewBag.Message = "Your application description page.";  
  29.   
  30.             return View();  
  31.         }  
  32.   
  33.         public ActionResult Contact()  
  34.         {  
  35.             ViewBag.Message = "Your contact page.";  
  36.   
  37.             return View();  
  38.         }  
  39.   
  40.   
  41.         [HttpPost]  
  42.         public  String WeatherDetail(string City)  
  43.         {  
  44.   
  45.             //Assign API KEY which received from OPENWEATHERMAP.ORG  
  46.             string appId = "8113fcc5a7494b0518bd91ef3acc074f";  
  47.   
  48.             //API path with CITY parameter and other parameters.  
  49.             string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&cnt=1&APPID={1}", City, appId);  
  50.   
  51.             using (WebClient client = new WebClient())  
  52.             {  
  53.                 string json = client.DownloadString(url);  
  54.                   
  55.                 //********************//  
  56.                 //     JSON RECIVED   
  57.                 //********************//  
  58.                 //{"coord":{ "lon":72.85,"lat":19.01},  
  59.                 //"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],  
  60.                 //"base":"stations",  
  61.                 //"main":{"temp":31.75,"feels_like":31.51,"temp_min":31,"temp_max":32.22,"pressure":1014,"humidity":43},  
  62.                 //"visibility":2500,  
  63.                 //"wind":{"speed":4.1,"deg":140},  
  64.                 //"clouds":{"all":0},  
  65.                 //"dt":1578730750,  
  66.                 //"sys":{"type":1,"id":9052,"country":"IN","sunrise":1578707041,"sunset":1578746875},  
  67.                 //"timezone":19800,  
  68.                 //"id":1275339,  
  69.                 //"name":"Mumbai",  
  70.                 //"cod":200}  
  71.   
  72.                 //Converting to OBJECT from JSON string.  
  73.                 RootObject weatherInfo = (new JavaScriptSerializer()).Deserialize<RootObject>(json);  
  74.   
  75.                 //Special VIEWMODEL design to send only required fields not all fields which received from   
  76.                 //www.openweathermap.org api  
  77.                 ResultViewModel rslt = new ResultViewModel();  
  78.   
  79.                 rslt.Country = weatherInfo.sys.country;  
  80.                 rslt.City = weatherInfo.name;  
  81.                 rslt.Lat = Convert.ToString(weatherInfo.coord.lat);  
  82.                 rslt.Lon = Convert.ToString(weatherInfo.coord.lon);  
  83.                 rslt.Description = weatherInfo.weather[0].description;  
  84.                 rslt.Humidity = Convert.ToString(weatherInfo.main.humidity);  
  85.                 rslt.Temp = Convert.ToString(weatherInfo.main.temp);  
  86.                 rslt.TempFeelsLike = Convert.ToString(weatherInfo.main.feels_like);  
  87.                 rslt.TempMax = Convert.ToString(weatherInfo.main.temp_max);  
  88.                 rslt.TempMin = Convert.ToString(weatherInfo.main.temp_min);  
  89.                 rslt.WeatherIcon = weatherInfo.weather[0].icon;  
  90.   
  91.                 //Converting OBJECT to JSON String   
  92.                 var jsonstring = new JavaScriptSerializer().Serialize(rslt);  
  93.   
  94.                 //Return JSON string.  
  95.                 return jsonstring;  
  96.             }  
  97.         }  
  98.   
  99.     }  
  100. }  
Happy Coding. . . .


Similar Articles