Climate Report Information Using An ASP.NET MVC And API Key

Introduction

Climate API key is a way to get the real time climate reports of any place of the world. You can use this API key free of cost in your ASP.NET MVC Application. To use Climate API, you have to register and get your own API key from here.

The link reference is - https://home.openweathermap.org/users/sign_up

Description

In this Application, you can put your required city name inside the country and outside the country along with city ID, followed by using climate API. You will get the details of climate information.

Refer

You can use this URL to get the City ID, Country name and Code.

http://openweathermap.org/help/city_list.txt

MVC

You should use the URL given below to pass the CITYID and APIKEY.

http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric

Steps to create MVC app, using climate API shows the detailed climate Information

Step 1

Create an Empty Template in an ASP.NET MVC app named “ClimateReport”.

MVC

Step 2

Create one model class file named “ClimateModel.cs”.

Code Ref

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace ClimateReport.Models  
  8. {  
  9.     public class ClimateModel  
  10.     {  
  11.         public string apiResponse { get; set; }  
  12.   
  13.         public Dictionary<string, string> cities  
  14.         {  
  15.             get;  
  16.             set;  
  17.         }  
  18.     }  
  19. }   

Code description

Here, I added one namespace for support attribute on the code.

using System.ComponentModel.DataAnnotations;

This model class file has 2 properties, which are given below.

  1. string
  2. dictionary.

The string property i.e. apiResponse will contain an API response. I can serialize the response JSON and convert it to HTML in the Controller before setting this in this string property i.e. apiResponse.

In the dictionary property, I can add the City Names and their ID's.

MVC

Step 3

Here, I added one New folder and Helper Class is named as "Class” & “ClimateApi.cs”.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ClimateReport.Class  
  7. {  
  8.     public class ClimateApi  
  9.     {  
  10.     }  
  11.     public class Coord  
  12.     {  
  13.         public double lon { get; set; }  
  14.         public double lat { get; set; }  
  15.     }  
  16.     public class Weather  
  17.     {  
  18.         public int id { get; set; }  
  19.         public string main { get; set; }  
  20.         public string description { get; set; }  
  21.         public string icon { get; set; }  
  22.     }  
  23.     public class Main  
  24.     {  
  25.         public double temp { get; set; }  
  26.         public int pressure { get; set; }  
  27.         public int humidity { get; set; }  
  28.         public int temp_min { get; set; }  
  29.         public int temp_max { get; set; }  
  30.     }  
  31.     public class Wind  
  32.     {  
  33.         public double speed { get; set; }  
  34.         public int deg { get; set; }  
  35.     }  
  36.     public class Clouds  
  37.     {  
  38.         public int all { get; set; }  
  39.     }  
  40.     public class Sys  
  41.     {  
  42.         public int type { get; set; }  
  43.         public int id { get; set; }  
  44.         public double message { get; set; }  
  45.         public string country { get; set; }  
  46.         public int sunrise { get; set; }  
  47.         public int sunset { get; set; }  
  48.     }  
  49.     public class ResponseWeather  
  50.     {  
  51.         public Coord coord { get; set; }  
  52.         public List<Weather> weather { get; set; }  
  53.         public string @base { get; set; }  
  54.         public Main main { get; set; }  
  55.         public int visibility { get; set; }  
  56.         public Wind wind { get; set; }  
  57.         public Clouds clouds { get; set; }  
  58.         public int dt { get; set; }  
  59.         public Sys sys { get; set; }  
  60.         public int id { get; set; }  
  61.         public string name { get; set; }  
  62.         public int cod { get; set; }  
  63.     }  
  64. }  

Code description

Here, I have added some classes and put some public access properties inside it. Using this class and properties, we can access the climate information, using an API. It will work like IntelliSense.

For example 

  1. public class Main  
  2. {  
  3.     public double temp  { get; set; }  
  4.     public int pressure { get; set; }  
  5.     public int humidity { get; set; }  
  6.     public int temp_min { get; set; }  
  7.     public int temp_max { get; set; }  
  8. }  

Here, I added one class name called “Main”. Inside Main class, I added some properties called pressure, humidity, temp_min , temp_max and they can be used publicly.

Like this, we can add other class and related public access properties.

Now, we can create one parent class named ResponseWeather.

Inside this parent class, I added predefined base classes and its objects with get and set properties.

For example

  1. public Main main { get; set; }  

Like this, we can add predefined base classes and its objects with get and set properties.

Inside parent class also, we added some public variables.

For example

  1. public int id { get; set; }  
  2. public int cod { get; set; }  

MVC

Trick to Create these classes

The purpose of those classes is to serialize JSON response You are creating these classes for a JSON, which is a very hard and tedious job. Using an online tool json2csharp, I made these classes very easily. You can use this tool to create these classes for any JSON, which you have. All you have to do is to add your JSON and click Generate button.

My JSON code is for these classes.

  1. {"coord":{"lon":139,"lat":35},  
  2. "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},  
  3. "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],  
  4. "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},  
  5. "wind":{"speed":7.31,"deg":187.002},  
  6. "rain":{"3h":0},  
  7. "clouds":{"all":92},  
  8. "dt":1369824698,  
  9. "id":1851632,  
  10. "name":"Shuzenji",  
  11. "cod":200}  

My generated C# code is based on the above mentioned My JSON code.

  1. public class Coord  
  2. {  
  3.     public int lon { get; set; }  
  4.     public int lat { get; set; }  
  5. }  
  6. public class Sys  
  7. {  
  8.     public string country { get; set; }  
  9.     public int sunrise { get; set; }  
  10.     public int sunset { get; set; }  
  11. }  
  12. public class Weather  
  13. {  
  14.     public int id { get; set; }  
  15.     public string main { get; set; }  
  16.     public string description { get; set; }  
  17.     public string icon { get; set; }  
  18. }  
  19. public class Main  
  20. {  
  21.     public double temp { get; set; }  
  22.     public int humidity { get; set; }  
  23.     public int pressure { get; set; }  
  24.     public double temp_min { get; set; }  
  25.     public double temp_max { get; set; }  
  26. }  
  27. public class Wind  
  28. {  
  29.     public double speed { get; set; }  
  30.     public double deg { get; set; }  
  31. }  
  32. public class Rain  
  33. {  
  34.     public int __invalid_name__3h { get; set; }  
  35. }  
  36. public class Clouds  
  37. {  
  38.     public int all { get; set; }  
  39. }  
  40. public class RootObject  
  41. {  
  42.     public Coord coord { get; set; }  
  43.     public Sys sys { get; set; }  
  44.     public List<Weather> weather { get; set; }  
  45.     public Main main { get; set; }  
  46.     public Wind wind { get; set; }  
  47.     public Rain rain { get; set; }  
  48.     public Clouds clouds { get; set; }  
  49.     public int dt { get; set; }  
  50.     public int id { get; set; }  
  51.     public string name { get; set; }  
  52.     public int cod { get; set; }  
  53. }  

Source To Create, using http://json2csharp.com online tool.

MVC

Step 4

Now, I have added one Controller class file named “ClimateMapController.cs”.

Code Ref

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Net;  
  7. using System.IO;  
  8. using System.Text;  
  9. using Newtonsoft.Json;  
  10. using ClimateReport.Class;  
  11. using ClimateReport.Models;  
  12.   
  13. namespace ClimateReport.Controllers  
  14. {  
  15.     public class ClimateMapController : Controller  
  16.     {  
  17.           
  18.         public ActionResult Index()  
  19.         {  
  20.             ClimateModel openWeatherMap = FillCity();  
  21.             return View(openWeatherMap);  
  22.         }  
  23.   
  24.         [HttpPost]  
  25.         public ActionResult Index(string cities)  
  26.         {  
  27.             ClimateModel openWeatherMap = FillCity();  
  28.   
  29.             if (cities != null)  
  30.             {  
  31.                  
  32.                 string apiKey = "Put Your Own Api Key";  
  33.                 HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest;  
  34.   
  35.                 string apiResponse = "";  
  36.                 using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)  
  37.                 {  
  38.                     StreamReader reader = new StreamReader(response.GetResponseStream());  
  39.                     apiResponse = reader.ReadToEnd();  
  40.                 }  
  41.                   
  42.                 ResponseWeather rootObject = JsonConvert.DeserializeObject<ResponseWeather>(apiResponse);  
  43.   
  44.                 StringBuilder sb = new StringBuilder();  
  45.                 sb.Append("<table><tr><th>Weather Description</th></tr>");  
  46.                 sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>");  
  47.                 sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>");  
  48.                 sb.Append("<tr><td>Country Sun Rise:</td><td>" + rootObject.sys.sunrise + "</td></tr>");  
  49.                 sb.Append("<tr><td>Country Sun Sete:</td><td>" + rootObject.sys.sunset + "</td></tr>");  
  50.                 sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>");  
  51.                 sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>");  
  52.                 sb.Append("<tr><td>Max. Temperature:</td><td>" + rootObject.main.temp_max + " °C</td></tr>");  
  53.                 sb.Append("<tr><td>Min. Temperature:</td><td>" + rootObject.main.temp_min + " °C</td></tr>");  
  54.                 sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + "</td></tr>");  
  55.                 sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>");  
  56.                 sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>");  
  57.                 sb.Append("</table>");  
  58.                 openWeatherMap.apiResponse = sb.ToString();  
  59.             }  
  60.             else  
  61.             {  
  62.                 if (Request.Form["submit"] != null)  
  63.                 {  
  64.                     TempData["SelectOption"] = -1;  
  65.                 }  
  66.             }  
  67.             return View(openWeatherMap);  
  68.         }  
  69.   
  70.         public ClimateModel FillCity()  
  71.         {  
  72.             ClimateModel openWeatherMap = new ClimateModel();  
  73.             openWeatherMap.cities = new Dictionary<string, string>();  
  74.             openWeatherMap.cities.Add("Mumbai""1275339");  
  75.             openWeatherMap.cities.Add("New Delhi""1261481");  
  76.             openWeatherMap.cities.Add("Bangalore""1277333");  
  77.             openWeatherMap.cities.Add("Bhubaneshwar""1275817");  
  78.             openWeatherMap.cities.Add("Khurda""1266616");  
  79.             openWeatherMap.cities.Add("Cuttack""1273780");  
  80.             openWeatherMap.cities.Add("Hyderabad""1269843");  
  81.             openWeatherMap.cities.Add("Philadelphia""4560349");  
  82.             return openWeatherMap;  
  83.         }  
  84.   
  85.     }  
  86. }  

Code description

Here, I added one namespace and assembly/dll file to access the system generated class of the predefined class files to support API related matter.

  1. using Newtonsoft.Json;  

The other two namespaces to access and inherit the properties and roles are given below. 

  1. using ClimateReport.Class;  
  2. using ClimateReport.Models;   

In an Index action result method of HttpGet attribute, I added my model class file. I created one function called FillCity() and assign to ClimateModel class object.

Get ActionResult Index will be called, whenever the Index view will load (and not reload when the button is clicked). In this, I am calling the FillCity() method to add city names and their Id's to the dictionary property of the modal. Finally, I returned this modal. This returns the model ( and its values ) to the index view.

  1. ClimateModel openWeatherMap = FillCity();  

In return view statement, I passed this model class object.

  1. return View(openWeatherMap);  

In an Index action result, method of HttpPost attribute I added my model class file.I created created one function called FillCity() and assign to ClimateModel class object.

  1. ClimateModel openWeatherMap = FillCity();  

The Post ActionResult Index will be called whenever the page is postback (through the button click). Actually in my View, I will have cities that a user can select in radio input control and a button, which when clicked should do API call and fetch the selected city’s weather.This means on clicking the button, this Post ActionResult will be called.This ActionResult has 1 parameters string cities.

It means the cities Parameter will get me the city Id of the selected city from the view (on the button click, of course).Next, I am making the OpenWeatherMap API call, using C# classes HttpWebRequest & HttpWebResponse. You need to add the namespace, using System.Net; to your Controller on the top. I am also using StreamReader class (namespace System.IO) to read the response (JSON). I now have the JSON, so let us serialize it. The serialization is done by JsonConvert class. You can add the reference to this from NuGet Package Manager.

With this line of code (ResponseWeather rootObject = JsonConvert.DeserializeObject<responseweather>(apiResponse);) I will fetch the values from JSON and add them to my Helper class. All this in 1 line of code and that purely due to the magic of JsonConvert class.

I am creating an HTML table, which contains the city weather details, using StringBuilder (namespace System.Text). The StringBuilder value is added to model apiResponse property.

I passed one string parameter in an Index action result method of HttpPost attribute. 

  1. [HttpPost]  
  2. public ActionResult Index(string cities)   

Put the condition of cities string parameter value, which is not null. It will append all the data related to climate information, which is based on the selection of the user.

I check, if the cities is not null, only then I will call API. This is done so that the user is bound to select at least one city radio input.

I used it for calling API.

http://openweathermap.org/api

I used my own generated API key, which is given below.

  1. string apiKey = "Put Your Own Api Key";  

To generate your own API key, follow the mentioned steps given above.

To make request of API key, we should use the HttpWebRequest class and WebRequest class files.

HttpWebRequest = This class provides http specific implementation of WebRequest class.

WebRequest = This abstract class makes a request to uniform resource identifier.

Now, we use one URL to pass the CITYID and an APIKEY.

http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric

For calling API, the codes are mentioned below. 

  1. string apiKey = " Put Your Own Api Key ";  
  2.                 HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=" + cities + "&appid=" + apiKey + "&units=metric") as HttpWebRequest;  
  3.   
  4.                 string apiResponse = "";  
  5.                 using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)  
  6.                 {  
  7.                     StreamReader reader = new StreamReader(response.GetResponseStream());  
  8.                     apiResponse = reader.ReadToEnd();  
  9.                 }   

Using an object of parent class “ResponseWeather” defined in Helper class, I will access some properties and respective roles.

Here, I used “JsonConvert” system defined class, which can be accessed through namespace 

  1. “using Newtonsoft.Json;”  
  2. ResponseWeather rootObject = JsonConvert.DeserializeObject<ResponseWeather>(apiResponse);   

This is related to http://json2csharp.com online tool.

Now, I will create one string builder class called “StringBuilder”.

Using an object of parent class “ResponseWeather” defined in Helper class, we can access all the properties and the roles. 

  1. StringBuilder sb = new StringBuilder();  
  2. sb.Append("<table><tr><th>Weather Description</th></tr>");  
  3.                 sb.Append("<tr><td>City:</td><td>" + rootObject.name + "</td></tr>");  
  4.                 sb.Append("<tr><td>Country:</td><td>" + rootObject.sys.country + "</td></tr>");  
  5.                 sb.Append("<tr><td>Country Sun Rise:</td><td>" + rootObject.sys.sunrise + "</td></tr>");  
  6.                 sb.Append("<tr><td>Country Sun Sete:</td><td>" + rootObject.sys.sunset + "</td></tr>");  
  7.                 sb.Append("<tr><td>Wind:</td><td>" + rootObject.wind.speed + " Km/h</td></tr>");  
  8.                 sb.Append("<tr><td>Current Temperature:</td><td>" + rootObject.main.temp + " °C</td></tr>");  
  9.                 sb.Append("<tr><td>Max. Temperature:</td><td>" + rootObject.main.temp_max + " °C</td></tr>");  
  10.                 sb.Append("<tr><td>Min. Temperature:</td><td>" + rootObject.main.temp_min + " °C</td></tr>");  
  11.                 sb.Append("<tr><td>Pressure:</td><td>" + rootObject.main.pressure + "</td></tr>");  
  12.                 sb.Append("<tr><td>Humidity:</td><td>" + rootObject.main.humidity + "</td></tr>");  
  13.                 sb.Append("<tr><td>Weather:</td><td>" + rootObject.weather[0].description + "</td></tr>");  
  14.                 sb.Append("</table>");  
  15.                 openWeatherMap.apiResponse = sb.ToString();   

If the user is not selected, just click the button and it will show one message to the end user.

If the cities value is null and button submit is clicked (when a user does not selects any city and clicks submit button), I can put “Choose Your Correct City” text inside the apiResponse property of the model. Here, I used one tempdata variable = -1 . Based on this tempdata value, the popup will be shown to thr end user . 

  1. else  
  2.    {  
  3.        if (Request.Form["submit"] != null)  
  4.        {  
  5.            //openWeatherMap.apiResponse = "Choose Your Correct City";  
  6.            TempData["SelectOption"] = -1;  
  7.        }  
  8.    }   

In return view statement, I passed this model class object.

  1. return View(openWeatherMap);  

I created one function, using model class file named “FillCity()”. Here, I added some City Name and City ID. Pass only these, using API, URL and get the details. 

  1. public ClimateModel FillCity()  
  2.         {  
  3.             ClimateModel openWeatherMap = new ClimateModel();  
  4.             openWeatherMap.cities = new Dictionary<string, string>();  
  5.             openWeatherMap.cities.Add("Mumbai""1275339");  
  6.             openWeatherMap.cities.Add("New Delhi""1261481");  
  7.             openWeatherMap.cities.Add("Bangalore""1277333");  
  8.             openWeatherMap.cities.Add("Bhubaneshwar""1275817");  
  9.             openWeatherMap.cities.Add("Khurda""1266616");  
  10.             openWeatherMap.cities.Add("Cuttack""1273780");  
  11.             openWeatherMap.cities.Add("Hyderabad""1269843");  
  12.             openWeatherMap.cities.Add("Philadelphia""4560349");  
  13.             return openWeatherMap;  
  14.         }   

Only these above mentioned cities will be shown in Output page and helps to fulfill your requirements.

If you want more, then you can add more city name along with the respective CityID, using URL.

http://openweathermap.org/help/city_list.txt

The work of this function is to add the city names and their Id's to the dictionary property of the Model.

MVC

Step 5

Now, I have added one view named Index.cshtml.

Code Ref 

  1. @model ClimateReport.Models.ClimateModel  
  2. <style>  
  3.     #SatyaDiv {  
  4.         padding-left: 20px;  
  5.     }  
  6.  
  7.         #SatyaDiv select, #SatyaDiv button {  
  8.             background-color: #4CAF50;  
  9.             border: none;  
  10.             color: white;  
  11.             padding: 15px 32px;  
  12.             text-align: center;  
  13.             text-decoration: none;  
  14.             display: inline-block;  
  15.             font-size: 16px;  
  16.             margin: 4px 2px;  
  17.             cursor: pointer;  
  18.             border-radius: 50%;  
  19.         }  
  20.  
  21.         #SatyaDiv #message table {  
  22.             width: 100%;  
  23.             border: solid 3px green;  
  24.             color: blue;  
  25.             font-style: oblique;  
  26.             font-family: Georgia;  
  27.             font-weight: bold;  
  28.             background: yellow;  
  29.         }  
  30.  
  31.             #SatyaDiv #message table th {  
  32.                 text-align: left;  
  33.                 color: white;  
  34.                 font-style: oblique;  
  35.                 background: Blue;  
  36.             }  
  37. </style>  
  38. @{ ViewBag.Title = "CLIMATE API IN ASP.NET MVC";}  
  39. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYA'S CLIMATE API TO GET CLIMATE REPORT OF PLACES</h2>  
  40. <fieldset>  
  41.     <legend style="font-family:Arial Black;color:blue">CHECK LATEST CLIMATE REPORT</legend>  
  42.     <div id="SatyaDiv">  
  43.         <h4 style="color:crimson">Choose Place To Check Climate Report</h4>  
  44.         @using (Html.BeginForm())  
  45.         {  
  46.             foreach (var city in Model.cities)  
  47.             {  
  48.                 <span>  
  49.                     @Html.RadioButtonFor(m => m.cities, city.Value) @city.Key  
  50.                 </span>  
  51.             }  
  52.   
  53.             <button name="submit">Show Report</button>  
  54.         }  
  55.         <div id="message">@(new HtmlString(Model.apiResponse))</div>  
  56.     </div>  
  57. </fieldset>  
  58. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
  59. <script>  
  60.     $(document).ready(function () {  
  61.         $("input[id='cities']").change(function () {  
  62.             $(this).parents("#SatyaDiv").find("span").css("background""none");  
  63.             $(this).parent().css("background""");  
  64.         });  
  65.     });  
  66. </script>  
  67.   
  68. @if (TempData["SelectOption"] != null)  
  69. {  
  70.     <script type="text/javascript">  
  71.         alert("Select Any One Place To Get Today's Latest Climate Report");  
  72.     </script>  
  73. }  
  74.   
  75. <footer>  
  76.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  77. </footer>   

Code description

I have added one namespace called “@model ClimateReport.Models.ClimateModel”.

I have created on CSS style sheet and inside it, I used one DIV ID called “#SatyaDiv”. 

  1. <style>  
  2.     #SatyaDiv {  
  3.         padding-left: 20px;  
  4.     }  
  5.  
  6.         #SatyaDiv select, #SatyaDiv button {  
  7.             background-color: #4CAF50;  
  8.             border: none;  
  9.             color: white;  
  10.             padding: 15px 32px;  
  11.             text-align: center;  
  12.             text-decoration: none;  
  13.             display: inline-block;  
  14.             font-size: 16px;  
  15.             margin: 4px 2px;  
  16.             cursor: pointer;  
  17.             border-radius: 50%;  
  18.         }  
  19.  
  20.         #SatyaDiv #message table {  
  21.             width: 100%;  
  22.             border: solid 3px green;  
  23.             color: blue;  
  24.             font-style: oblique;  
  25.             font-family: Georgia;  
  26.             font-weight: bold;  
  27.             background: yellow;  
  28.         }  
  29.  
  30.             #SatyaDiv #message table th {  
  31.                 text-align: left;  
  32.                 color: white;  
  33.                 font-style: oblique;  
  34.                 background: Blue;  
  35.             }  
  36. </style>   

For button style purpose, I added the code, as shown below. 

  1. #SatyaDiv select, #SatyaDiv button {  
  2.             background-color: #4CAF50;  
  3.             border: none;  
  4.             color: white;  
  5.             padding: 15px 32px;  
  6.             text-align: center;  
  7.             text-decoration: none;  
  8.             display: inline-block;  
  9.             font-size: 16px;  
  10.             margin: 4px 2px;  
  11.             cursor: pointer;  
  12.             border-radius: 50%;  
  13.         }   

For table data and table header style, I added the code, as shown below. 

  1. #SatyaDiv #message table {  
  2.      width: 100%;  
  3.      border: solid 3px green;  
  4.      color: blue;  
  5.      font-style: oblique;  
  6.      font-family: Georgia;  
  7.      font-weight: bold;  
  8.      background: yellow;  
  9.  }  
  10.  
  11.      #SatyaDiv #message table th {  
  12.          text-align: left;  
  13.          color: white;  
  14.          font-style: oblique;  
  15.          background: Blue;  
  16.      }   

Now, I put radio buttons control and submit button.

The radio button lists come from model class function, as defined in controller class file. 

  1. foreach (var city in Model.cities)  
  2.             {  
  3.                 <span>  
  4.                     @Html.RadioButtonFor(m => m.cities, city.Value) @city.Key  
  5.                 </span>  
  6.             }  
  7.   
  8. <button name="submit">Show Report</button>  
  9. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
  10. <script>  
  11.     $(document).ready(function () {  
  12.         $("input[id='cities']").change(function () {  
  13.             $(this).parents("#SatyaDiv").find("span").css("background""none");  
  14.             $(this).parent().css("background""");  
  15.         });  
  16.     });  
  17. </script>   

Here, I used one jQuery script file to change the color of an input radio button and for this, I have to add jQuery script file reference path.

  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  

Here, I used one popup message, which is based on tempdata variable value, if the user did not select any radio button and just select Submit button. 

  1. @if (TempData["SelectOption"] != null)  
  2. {  
  3.     <script type="text/javascript">  
  4.         alert("Select Any One Place To Get Today's Latest Climate Report");  
  5.     </script>  
  6. }   

Also, you can use this message type instead of JavaScript alert.

  1. <div id="message">@(new HtmlString(Model.apiResponse))</div>  

Here, in “Model.apiResponse” area, you should manually put the warning message and show to the end user.

  1. openWeatherMap.apiResponse = "Choose Your Correct City";  

Here, I added current date time in the footer section. 

  1. <footer>  
  2.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  3. </footer>   

A view forms UI of MVC Application.

I added the reference to the Modal class “@model ClimateReport.Models.ClimateModel”. This is because the model class will transfer the values from the Controller to the view.

  1. @using (Html.BeginForm())  

This code is for creating a form. MVC form is created with Html.BeginForm()). Note that in MVC when the form contains a button, only then the button will causes the Postback.

Now, I create "#SatyaDiv” div and inside it, I created another form, which contains the city radio input controls and a submit button.To create the city radio button, I am looping through the dictionary property of the modal (cities). Now, I am creating them, using an MVC premade function- Html.RadioButtonFor(m => m.cities, city.Value).@city. Key will show the city names on the view.

@(new HtmlString(Model.apiResponse)) will show an HTML table or text “Choose Your Correct City” inside the message div.

This means the message div will show the weather details of the selected city to the users.

I added few lines of jQuery code. 

  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
  2. <script>  
  3.     $(document).ready(function () {  
  4.         $("input[id='cities']").change(function () {  
  5.             $(this).parents("#SatyaDiv").find("span").css("background""none");  
  6.             $(this).parent().css("background""green");  
  7.         });  
  8.     });  
  9. </script>   

Now, proceed, as shown below.
MVC

Step 6

Configure URL setting of this MVC app.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace ClimateReport  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "ClimateMap", action = "Index", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }   

Code description

Here, controller name is ClimateMap and controller action method name is an Index.

It is related with View or UI of this MVC app.

MVC

Step 7

You should have compulsory internet connection to access this feature of jQuery Script as well as this Climate API key.

Pic Refs

MVC

MVC

Without an internet connection, this jQuery scipt file can’t be downloaded and the feature is unable to be seen. 

Output

The URL of this MVC app is given below.

http://localhost:54445/ClimateMap/Index

Here, controller name is ClimateMap and controller action method name is an Index.

MVC

Without the selection of any city radio button, if we click Show Report button you will get a warning message.

MVC

Select any city radio button and the climate details will come.

When you select Bangalore, it displays, as shown below.

MVC

When you select Philadelphia, it will be displayed, as shown below.

MVC

Here, you can see the City name, Country name, Temperature and Pressure, as defined in controller class file etc.

MVC

Here, you can check footer section of this climate MVC application .

Summary

  1. How to get climate API key
  2. How to get city name and city ID
  3. How the API key and city ID passed to the earlier mentioned URL in controller class file
  4. How to use inside MVC Application to get the latest climate information report