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 register yourself and get an API key:

https://www.openweathermap.org/

Display

Create a project called “WeatherForecast”

Installed

Select MVC

No authentication

Select the following things as per the image.

MVC

After pressing OK, Visual Studio creates the project WeatherForecast.

Microsoft visual studio

Now switch to HomeController and create a new action method called “Weather”.

public ActionResult Weather()
{
    return View();
}

Create a Weather view.

Right-click on Weather action method ---> Add View

Seach city 

Switch to Weather.cshtml file add the following code.

@{
    ViewBag.Title = "Weather";
}
<h1>Search City and Get Weather Forecast</h1>
<div>
    <strong>City Name:</strong><input id="txtCity" type="text" />
    <br />
    <br />
    <button id="btnSubmit">Get Weather Forecast</button>
</div>
<div>
    <h2>Weather Forecast</h2>
    <table>
        <tr>
            <td>Weather Symbol Icon <img id="imgWeatherIconUrl" src="" title="Weather Icon" /></td>
        </tr>
        <tr>
            <td>
                <strong>City: </strong>
                <span id="lblCity"></span>,
                <span id="lblCountry"></span>
            </td>
        </tr>
        <tr>
            <td>
                <strong>Latitude: </strong>
                <label id="lblLat"></label><br />
                <strong>Longitude: </strong>
                <label id="lblLon"></label>
            </td>
        </tr>
        <tr>
            <td>
                <strong>Description:</strong>
                <label id="lblDescription"></label><br />
                <strong>Humidity:</strong>
                <label id="lblHumidity"></label>
            </td>
        </tr>
        <tr>
            <td>
                Temperature (Feels Like) <label id="lblTempFeelsLike"></label><br />
                Temperature <label id="lblTemp"></label><br />
                Temperature (Min) <label id="lblTempMin"></label><br />
                Temperature (Max) <label id="lblTempMax"></label><br />
            </td>
        </tr>
    </table>
</div>
<script>
    $("#btnSubmit").click(function () {
        var cityname = $("#txtCity").val();
        if (cityname.length > 0) {
            $.ajax({
                url: "http://localhost:52189/Home/WeatherDetail?City=" + cityname,
                type: "POST",
                success: function (rsltval) {
                    var data = JSON.parse(rsltval);
                    console.log(data);
                    $("#lblCity").html(data.City);
                    $("#lblCountry").text(data.Country);
                    $("#lblLat").text(data.Lat);
                    $("#lblLon").text(data.Lon);
                    $("#lblDescription").text(data.Description);
                    $("#lblHumidity").text(data.Humidity);
                    $("#lblTempFeelsLike").text(data.TempFeelsLike);
                    $("#lblTemp").text(data.Temp);
                    $("#lblTempMax").text(data.TempMax);
                    $("#lblTempMin").text(data.TempMin);
                    $("#imgWeatherIconUrl").attr("src", "http://openweathermap.org/img/w/" + data.WeatherIcon + ".png");
                },
                error: function () {
                    alert("Error retrieving weather data.");
                }
            });
        } else {
            alert("City Not Found");
        }
    });
</script>

OUTPUT of Weather.CSS HTML

Weather forecast

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:

{
    "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 a 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 a file called WeatherViewModel.cs.

Right-click on the MODELS folder, select ADD-->CLASS

WeatherViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WeatherForecast.Models
{
    public class ResultViewModel
    {
        public string City { get; set; }
        public string Country { get; set; }
        public string Lat { get; set; }
        public string Lon { get; set; }
        public string Description { get; set; }
        public string Humidity { get; set; }
        public string TempFeelsLike { get; set; }
        public string Temp { get; set; }
        public string TempMax { get; set; }
        public string TempMin { get; set; }
        public string WeatherIcon { get; set; }
    }
    public class Coord
    {
        public double lon { get; set; }
        public double lat { get; set; }
    }
    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }
    public class Main
    {
        public double temp { get; set; }
        public double feels_like { get; set; }
        public int temp_min { get; set; }
        public double temp_max { get; set; }
        public int pressure { get; set; }
        public int humidity { get; set; }
    }
    public class Wind
    {
        public double speed { get; set; }
        public int deg { get; set; }
    }
    public class Clouds
    {
        public int all { get; set; }
    }
    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }
    public class RootObject
    {
        public Coord coord { get; set; }
        public List<Weather> weather { get; set; }
        public string @base { get; set; }
        public Main main { get; set; }
        public int visibility { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public Sys sys { get; set; }
        public int timezone { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }
}

Switch again to HomeController to write the method to fetch the response/data from OPENWEATHERMAP.ORG through the api.

Following NAMESPACES ADDED

using System.Net;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using WeatherForecast.Models;
[HttpPost]
public String WeatherDetail(string City)
{
    // Assign API KEY which received from OPENWEATHERMAP.ORG
    string appId = "8113fcc5a7494b0518bd91ef3acc074f";
    // API path with CITY parameter and other parameters.
    string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&cnt=1&APPID={1}", City, appId);
    using (WebClient client = new WebClient())
    {
        string json = client.DownloadString(url);
        //********************//
        //      JSON RECEIVED    
        //********************//
        // {"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}
        // Converting to OBJECT from JSON string.
        RootObject weatherInfo = (new JavaScriptSerializer()).Deserialize<RootObject>(json);
        // Special VIEWMODEL design to send only required fields not all fields which received from    
        // www.openweathermap.org api
        ResultViewModel rslt = new ResultViewModel();
        rslt.Country = weatherInfo.sys.country;
        rslt.City = weatherInfo.name;
        rslt.Lat = Convert.ToString(weatherInfo.coord.lat);
        rslt.Lon = Convert.ToString(weatherInfo.coord.lon);
        rslt.Description = weatherInfo.weather[0].description;
        rslt.Humidity = Convert.ToString(weatherInfo.main.humidity);
        rslt.Temp = Convert.ToString(weatherInfo.main.temp);
        rslt.TempFeelsLike = Convert.ToString(weatherInfo.main.feels_like);
        rslt.TempMax = Convert.ToString(weatherInfo.main.temp_max);
        rslt.TempMin = Convert.ToString(weatherInfo.main.temp_min);
        rslt.WeatherIcon = weatherInfo.weather[0].icon;
        // Converting OBJECT to JSON String    
        var jsonstring = new JavaScriptSerializer().Serialize(rslt);
        // Return JSON string.
        return jsonstring;
    }
}

Note. Before running the project switch _layout. cshtml, which is located inside the 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,

Get weather forecast button

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>

WeatherViewModel.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WeatherForecast.Models
{
    public class ResultViewModel
    {
        public string City { get; set; }
        public string Country { get; set; }
        public string Lat { get; set; }
        public string Lon { get; set; }
        public string Description { get; set; }
        public string Humidity { get; set; }
        public string TempFeelsLike { get; set; }
        public string Temp { get; set; }
        public string TempMax { get; set; }
        public string TempMin { get; set; }
        public string WeatherIcon { get; set; }
    }
    public class Coord
    {
        public double lon { get; set; }
        public double lat { get; set; }
    }
    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }
    public class Main
    {
        public double temp { get; set; }
        public double feels_like { get; set; }
        public int temp_min { get; set; }
        public double temp_max { get; set; }
        public int pressure { get; set; }
        public int humidity { get; set; }
    }
    public class Wind
    {
        public double speed { get; set; }
        public int deg { get; set; }
    }
    public class Clouds
    {
        public int all { get; set; }
    }
    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }
    public class RootObject
    {
        public Coord coord { get; set; }
        public List<Weather> weather { get; set; }
        public string @base { get; set; }
        public Main main { get; set; }
        public int visibility { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public Sys sys { get; set; }
        public int timezone { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }
}

Weather. cshtml code

@{
    ViewBag.Title = "Weather";
}
<h1>Search City and Get Weather Forecast</h1>
<div>
    <strong>City Name :</strong><input id="txtCity" type="text"/>
    <br />
    <br />
    <button id="btnSubmit">Get Weather Forecast</button>
</div>
<div>
    <h2>Weather Forecast</h2>
    <table>
        <tr>
            <td>Weather Symbol Icon <img id="imgWeatherIconUrl" src="" title="Weather Icon" /></td>
        </tr>
        <tr>
            <td>
                <strong>City:</strong>
                <span id="lblCity"></span> ,
                <span id="lblCountry"></span>
            </td>
        </tr>
        <tr>
            <td>
                <strong>Latitude:</strong>
                <label id="lblLat"></label><br />
                <strong>Longitude:</strong>
                <label id="lblLon"></label>

            </td>
        </tr>
        <tr>
            <td>
                <strong>Description:</strong>
                <label id="lblDescription"></label><br />
                <strong>Humidity:</strong>
                <label id="lblHumidity"></label>
            </td>
        </tr>
        <tr>
            <td>
                Temperature (Feels Like)<label id="lblTempFeelsLike"></label><br />
                Temperature <label id="lblTemp"></label><br />
                Temperature (Min)<label id="lblTempMin"></label><br />
                Temperature (Max)<label id="lblTempMax"></label><br />
            </td>
        </tr>
    </table>
</div>
<script>
    $("#btnSubmit").click(function () {
        var cityname = $("#txtCity").val();
        if (cityname.length > 0)
        {
            $.ajax({
                url: "http://localhost:52189/Home/WeatherDetail?City="+cityname,
                type: "POST",
                success: function (rsltval) {
                    var data = JSON.parse(rsltval);
                    console.log(data);
                    $("#lblCity").html(data.City);
                    $("#lblCountry").text(data.Country);
                    $("#lblLat").text(data.Lat);
                    $("#lblLon").text(data.Lon);
                    $("#lblDescription").text(data.Description);
                    $("#lblHumidity").text(data.Humidity);
                    $("#lblTempFeelsLike").text(data.TempFeelsLike);
                    $("#lblTemp").text(data.Temp);
                    $("#lblTempMax").text(data.TempMax);
                    $("#lblTempMin").text(data.TempMin);
                    $("#imgWeatherIconUrl").attr("src", "http://openweathermap.org/img/w/" + data.WeatherIcon + ".png");
                },
                error: function () {

                }
            });
        }
        else
        {
            alert("City Not Found");
        }
    });
</script>

HomeController.cs code 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using WeatherForecast.Models;
namespace WeatherForecast.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Weather()
        {
            return View();
        }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
        [HttpPost]
        public String WeatherDetail(string City)
        {
            //Assign API KEY which received from OPENWEATHERMAP.ORG
            string appId = "8113fcc5a7494b0518bd91ef3acc074f";
            //API path with CITY parameter and other parameters.
            string url = string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&units=metric&cnt=1&APPID={1}", City, appId);
            using (WebClient client = new WebClient())
            {
                string json = client.DownloadString(url);
                //Converting to OBJECT from JSON string.
                RootObject weatherInfo = (new JavaScriptSerializer()).Deserialize<RootObject>(json);
                //Special VIEWMODEL design to send only required fields not all fields which received from    
                //www.openweathermap.org api
                ResultViewModel rslt = new ResultViewModel();
                rslt.Country = weatherInfo.sys.country;
                rslt.City = weatherInfo.name;
                rslt.Lat = Convert.ToString(weatherInfo.coord.lat);
                rslt.Lon = Convert.ToString(weatherInfo.coord.lon);
                rslt.Description = weatherInfo.weather[0].description;
                rslt.Humidity = Convert.ToString(weatherInfo.main.humidity);
                rslt.Temp = Convert.ToString(weatherInfo.main.temp);
                rslt.TempFeelsLike = Convert.ToString(weatherInfo.main.feels_like);
                rslt.TempMax = Convert.ToString(weatherInfo.main.temp_max);
                rslt.TempMin = Convert.ToString(weatherInfo.main.temp_min);
                rslt.WeatherIcon = weatherInfo.weather[0].icon;
                //Converting OBJECT to JSON String
                var jsonstring = new JavaScriptSerializer().Serialize(rslt);
                //Return JSON string.
                return jsonstring;
            }
        }
    }
}

Happy Coding. . . .


Similar Articles