Display Capital name based on Country using AngularJS in ASP.Net

Last Reply 7 months ago By dharmendr

Posted 7 months ago

How to display country and its capital list in agularjs in asp.net.

Posted 7 months ago

Hi rani,

Check this example. Now please take its reference and correct your code.

For reading json from url i have used below article.

Read (Parse) JSON data from URL and display in ASP.Net GridView using C# and VB.Net

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', []);
    app.controller('MyController', function ($scope, $http, $window) {
        $http.post("Default.aspx/PopulateCustomers", { headers: { 'Content-Type': 'application/json'} })
        .then(function (response) {
            $scope.Customers = response.data.d;
        }, function error(response) {
            alert(response.responseText);
        });
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Country</th>
                <th>Capital</th>
                <th>Flag</th>
                <th>Currency</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="customer in Customers">
                <td>{{ customer.Id }}</td>
                <td>{{ customer.Name }}</td>
                <td>{{ customer.Country }}</td>
                <td>{{ customer.Capital }}</td>
                <td><img alt="{{customer.Country}}" ng-src="{{customer.Flag}}" style="height: 25px; width: 25px" /></td>
                <td>{{ customer.Currency }}</td>
            </tr>
        </tbody>
    </table>
</div>

Namespaces

C#

using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Net;
using System.Web.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

VB.Net

Imports System.Collections.Generic
Imports System.Data
Imports System.Globalization
Imports System.Net
Imports System.Web.Services
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Code

C#

[WebMethod]
public static List<Customer> PopulateCustomers()
{
    // Get data from Database.
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] {
            new DataColumn("Id", typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Country",typeof(string)) });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Elizabeth Lincoln", "Canada");
    dt.Rows.Add(4, "Zhi Ruo", "China");
    dt.Rows.Add(5, "Roland Mendel", "Austria");

    List<Customer> customers = new List<Customer>();
    foreach (DataRow dr in dt.Rows)
    {
        customers.Add(new Customer
        {
            Id = Convert.ToInt32(dr["Id"]),
            Name = dr["Name"].ToString(),
            Country = dr["Country"].ToString(),
            Flag = "http://www.geognos.com/api/en/countries/flag/" + GetCountryCode(dr["Country"].ToString()) + ".png",
            Currency = GetCurrencySymbol(dr["Country"].ToString()),
            Capital = GetCapital(dr["Country"].ToString())
        });
    }

    return customers;
}
// Get Country Code from Country Name.
public static string GetCountryCode(string country)
{
    string countryCode = "";
    CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
    foreach (CultureInfo culture in cultures)
    {
        RegionInfo region = new RegionInfo(culture.LCID);
        if (region.EnglishName.ToUpper().Contains(country.ToUpper()))
        {
            countryCode = region.TwoLetterISORegionName;
            break;
        }
    }

    return countryCode;
}
// Get Currency Symbol from Country Name.
public static string GetCurrencySymbol(string country)
{
    string currencySymbol = "";
    CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
    foreach (CultureInfo culture in cultures)
    {
        RegionInfo region = new RegionInfo(culture.LCID);
        if (region.EnglishName.ToUpper().Contains(country.ToUpper()))
        {
            currencySymbol = region.CurrencySymbol;
            break;
        }
    }

    return currencySymbol;
}
// Get Capital name from Country Name.
public static string GetCapital(string country)
{
    string capitalName = "";
    string url = string.Format("http://www.geognos.com/api/en/countries/info/{0}.json", GetCountryCode(country));
    using (WebClient client = new WebClient())
    {
        string json = client.DownloadString(url);
        JObject weatherInfo = JsonConvert.DeserializeObject<JObject>(json);
        capitalName = ((JToken)weatherInfo["Results"])["Capital"]["Name"].ToString().Replace("\"", string.Empty);
    }

    return capitalName;
}
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public string Flag { get; set; }
    public string Currency { get; set; }
    public string Capital { get; set; }
}

VB.Net

<WebMethod()>
Public Shared Function PopulateCustomers() As List(Of Customer)
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn(2) {
                        New DataColumn("Id", GetType(Integer)),
                        New DataColumn("Name", GetType(String)),
                        New DataColumn("Country", GetType(String))})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Elizabeth Lincoln", "Canada")
    dt.Rows.Add(4, "Zhi Ruo", "China")
    dt.Rows.Add(5, "Roland Mendel", "Austria")
    Dim customers As List(Of Customer) = New List(Of Customer)()
    For Each dr As DataRow In dt.Rows
        customers.Add(New Customer With {
            .Id = Convert.ToInt32(dr("Id")),
            .Name = dr("Name").ToString(),
            .Country = dr("Country").ToString(),
            .Flag = "http://www.geognos.com/api/en/countries/flag/" & GetCountryCode(dr("Country").ToString()) & ".png",
            .Currency = GetCurrencySymbol(dr("Country").ToString()),
            .Capital = GetCapital(dr("Country").ToString())
        })
    Next

    Return customers
End Function
' Get Country Code from Country Name.
Public Shared Function GetCountryCode(ByVal country As String) As String
    Dim countryCode As String = ""
    Dim cultures As CultureInfo() = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
    For Each culture As CultureInfo In cultures
        Dim region As RegionInfo = New RegionInfo(culture.LCID)
        If region.EnglishName.ToUpper().Contains(country.ToUpper()) Then
            countryCode = region.TwoLetterISORegionName
            Exit For
        End If
    Next

    Return countryCode
End Function
' Get Currency Symbol from Country Name.
Public Shared Function GetCurrencySymbol(ByVal country As String) As String
    Dim currencySymbol As String = ""
    Dim cultures As CultureInfo() = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
    For Each culture As CultureInfo In cultures
        Dim region As RegionInfo = New RegionInfo(culture.LCID)
        If region.EnglishName.ToUpper().Contains(country.ToUpper()) Then
            currencySymbol = region.CurrencySymbol
            Exit For
        End If
    Next

    Return currencySymbol
End Function
' Get Capital name from Country Name.
Public Shared Function GetCapital(ByVal country As String) As String
    Dim capitalName As String = ""
    Dim url As String = String.Format("http://www.geognos.com/api/en/countries/info/{0}.json", GetCountryCode(country))
    Using client As WebClient = New WebClient()
        Dim json As String = client.DownloadString(url)
        Dim weatherInfo As JObject = JsonConvert.DeserializeObject(Of JObject)(json)
        capitalName = (CType(weatherInfo("Results"), JToken))("Capital")("Name").ToString().Replace("""", String.Empty)
    End Using

    Return capitalName
End Function

Public Class Customer
    Public Property Id As Integer
    Public Property Name As String
    Public Property Country As String
    Public Property Flag As String
    Public Property Currency As String
    Public Property Capital As String
End Class

Screenshot