Xamarin : How to call API POST method




Xamarin : API call



How to consume API method in xamarin application ? 

I tried on google but couldn't find proper example. I got help of my friend who have knowledge of xamarin and some help from google, and created successful demo, which I am sharing with you.

Steps:
  1. First check that API is working or not
  2. Install "newtonsoft json" from NuGet package manager


Design 


<Grid>



    <Grid.RowDefinitions>

      <RowDefinition Height="50"></RowDefinition>

      <RowDefinition Height="50"></RowDefinition>

      <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"></ColumnDefinition>      
    </Grid.ColumnDefinitions>

    <Button Text="Get Data"
            Clicked="OnGetDataButtonClicked"
            Grid.Row="0"
            Grid.Column="0"></Button>
    <Label x:Name="lblMsg"
           Grid.Row="1"
           Grid.Column="0"></Label>

    <ListView x:Name="MainList"  ItemTapped="OnTapped" Grid.Row="2" Grid.Column="0"> 
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Orientation="Horizontal">
              <Label Text="{Binding EmailId}"></Label> 
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    
  </Grid>


Code

async void OnGetDataButtonClicked(object sender, EventArgs e)
        {
            try
            {
                HttpClient client = new HttpClient();

                string requestPayload = @"{
""UserId"": ""123"",
""dataTableCommon"":{
""param"" :{""Start"": ""21"",
""Length"": ""10"",
""Draw"" :""1""}
}
}";
                var response = await client.PostAsync("http://Domainname/DemoAPI/API/User/GetUsersList", 
new StringContent(requestPayload, Encoding.UTF8, "application/json"));

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var json = await response.Content.ReadAsStringAsync();
   
                    //Here you need to create class for output results
    // To generate class, you can use http://json2csharp.com

                    var results = JsonConvert.DeserializeObject<RootObject>(json);

                    MainList.ItemsSource = results.data;                    
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
            }            
        }

        void OnTapped(object sender, ItemTappedEventArgs e)
        {
            var selected = e.Item as Users;

            DisplayAlert("Name", selected.FirstName + " " + selected.LastName, "Okay");
        }


Generate Class

    // To generate class, you can use http://json2csharp.com

    

    public class Users

    {

        public string UserId { get; set; }    

        public string FirstName { get; set; }

        public string LastName { get; set; }
        public string EmailId { get; set; }
    }

    public class RootObject
    {        
        public List<Users> data { get; set; } 
    }


Output


























































I hope, you like the article !!! ENJOY !!!



Xamarin : Resource Contents - Stylesheet



Xamarin : Resource Contents - Stylesheet


Design Page

<ContentPage.Resources>
    <ResourceDictionary>
      <Style x:Key="ColorfullLabel" TargetType="Label">
        <Setter Property="TextColor" Value="Red"></Setter>
        <Setter Property="BackgroundColor" Value="Yellow"></Setter>
      </Style>
      <Style x:Key="lblMargin" TargetType="Label">
        <Setter Property="Margin" Value="20"></Setter>
        <Setter Property="FontSize" Value="20"></Setter>
      </Style>
      <Style x:Key="btnMargin" TargetType="Button">
        <Setter Property="Margin" Value="20"></Setter>
        <Setter Property="FontSize" Value="20"></Setter>
        <Setter Property="Rotation" Value="20"></Setter>
        <Setter Property="BorderWidth" Value="20"></Setter>
      </Style>
    </ResourceDictionary>
  </ContentPage.Resources>
  
  <StackLayout Orientation="Vertical">

    <Label Text="Different color"
           Style="{StaticResource ColorfullLabel}"></Label>

    <Label Text="Font Size"
           FontSize="20"></Label>

    <Label Text="Margin"
           Style="{StaticResource lblMargin}"></Label>

    <Label Text="Italic"
           FontAttributes="Italic"></Label>

    <Label Text="Left Justified"
           HorizontalTextAlignment="End"
           FontSize="Large"></Label>

    <Label Text="Hello, World!"
         VerticalOptions="Start"
         HorizontalTextAlignment="Center"
         Rotation="-15"
         IsVisible="true"
         FontSize="Large"
         FontAttributes="Bold"
         TextColor="Blue" />

    <Button Text="Verticle Button"
        Style="{StaticResource btnMargin}">
    </Button>

  </StackLayout>

Xamarin : Button Formatting & Click Event


Xamarin : Button Formatting & Click Event


Design


<StackLayout Orientation="Vertical">

    <Button Text="Different color"
           TextColor="Yellow"
           BackgroundColor="Blue"></Button>

    <Button Text="Font Size"
           FontSize="20">
    </Button>

    <Button Text="Margin"
           Margin="20"></Button>

    <Button Text="Center"
           HorizontalOptions="Center"
            VerticalOptions="Center">
    </Button>

    <Button Text="Verticle Button"
           Rotation="20"
            BorderWidth="20" Clicked="btnClick">
    </Button>

  </StackLayout>


Code:


       void btnClick(object sender, EventArgs e)
        {
            DisplayAlert("Button Click", "You clicked on button :)", "Okay");
        }

Xamarin : Label Formatting




Xamarin : Label Formatting



<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.NewPage"
             Title="Label Formatting">

  <StackLayout Orientation="Vertical">
 
    <Label Text="Different color"
           TextColor="Red"
           BackgroundColor="Yellow"></Label>
 
    <Label Text="Font Size"
           FontSize="20"></Label>
 
    <Label Text="Margin"
           Margin="20"></Label>
 
    <Label Text="Italic"
           FontAttributes="Italic"></Label>
 
    <Label Text="Left Justified"
           HorizontalTextAlignment="End"
           FontSize="Large"></Label>

     <Label Text="Hello, World!"
         VerticalOptions="Start"
         HorizontalTextAlignment="Center"
         Rotation="-15"
         IsVisible="true"
         FontSize="Large"
         FontAttributes="Bold"
         TextColor="Blue" />
 
  </StackLayout>

</ContentPage>


  • Run the application







Xamarin : OnTapped navigation to new page




Xamarin : OnTapped navigation to new page


  • Add listview  in page

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 x:Class="App1.MainMaster"
 Title="My Application">
  <ListView x:Name="MainListItemTapped="OnTapped">
<ListView.ItemTemplate>
  <DataTemplate>
<ViewCell>
  <StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}"></Label>
<Label Text="{Binding Description}"></Label>
<Label Text="{Binding OrderNumber}"></Label>
  </StackLayout>
</ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>
  </ListView>
</ContentPage>


  • Write a code to bind listview 

public partial class MainMaster : ContentPage
{
public MainMaster()
{
InitializeComponent();
MainList.ItemsSource = new List<ListViewTemplate>
{
new ListViewTemplate { Name="One", Description="One", OrderNumber=1 },
new ListViewTemplate { Name="Two", Description="Two", OrderNumber=2 },
new ListViewTemplate { Name="Three", Description="Three", OrderNumber=3 }, new ListViewTemplate { Name="Four", Description="Four", OrderNumber=4 },
new ListViewTemplate { Name="Five", Description="Five", OrderNumber=5 },
};
}
}



  • Add new page, I set name "NewPage"




         async void OnTapped(object sender, ItemTappedEventArgs e)
        {
            var selected = e.Item as ListViewTemplate;

            switch (selected.OrderNumber)
            {
                case 1:
                    await Navigation.PushAsync(new NewPage());
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
            }

            //Set not to selected item : optional
            ((ListView)sender).SelectedItem = null;
        }


  • Set page in to run the application

public class App : Application
{
public App()
{
MainPage = new NavigationPage(new MainMaster());
}

}

  • Run the application





    Xamarin : OnTapped (on clicked) item in listview




    Xamarin : OnTapped (on clicked) item in listview


    • Add listview  in page

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     x:Class="App1.MainMaster"
     Title="My Application">
      <ListView x:Name="MainListItemTapped="OnTapped">
    <ListView.ItemTemplate>
      <DataTemplate>
    <ViewCell>
      <StackLayout Orientation="Horizontal">
    <Label Text="{Binding Name}"></Label>
    <Label Text="{Binding Description}"></Label>
    <Label Text="{Binding OrderNumber}"></Label>
      </StackLayout>
    </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
      </ListView>
    </ContentPage>


    • Write a code to bind listview 

    public partial class MainMaster : ContentPage
    {
    public MainMaster()
    {
    InitializeComponent();
    MainList.ItemsSource = new List<ListViewTemplate>
    {
    new ListViewTemplate { Name="One", Description="One", OrderNumber=1 },
    new ListViewTemplate { Name="Two", Description="Two", OrderNumber=2 },
    new ListViewTemplate { Name="Three", Description="Three", OrderNumber=3 }, new ListViewTemplate { Name="Four", Description="Four", OrderNumber=4 },
    new ListViewTemplate { Name="Five", Description="Five", OrderNumber=5 },
    };
    }
    }

            void OnTapped(object sender, ItemTappedEventArgs e)
            {
                var selected = e.Item as ListViewTemplate;
                DisplayAlert("Item Selecte", selected.Name, "Okay");
            }


    • Set page in to run the application

    public class App : Application
    {
    public App()
    {
    MainPage = new MainMaster();
    }

    }

    • Run the application




    Xamarin : Create simple List







    • Create new page



    • Create new class for listing properties
    public class ListViewTemplate
    {
    public string Name { get; set; }
    public string Description { get; set; }
    public int OrderNumber { get; set; }
    }




    • Add listview  in page

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="App1.MainMaster"
    Title="My Application">
     <ListView x:Name="MainList">
    <ListView.ItemTemplate>
     <DataTemplate>
    <ViewCell>
     <StackLayout Orientation="Horizontal">
    <Label Text="{Binding Name}"></Label>
    <Label Text="{Binding Description}"></Label>
    <Label Text="{Binding OrderNumber}"></Label>
     </StackLayout>
    </ViewCell>
     </DataTemplate>
    </ListView.ItemTemplate>
     </ListView>
    </ContentPage>


    • Write a code to bind listview 


    public partial class MainMaster : ContentPage
    {
    public MainMaster()
    {
    InitializeComponent();
    MainList.ItemsSource = new List<ListViewTemplate>
    {
    new ListViewTemplate { Name="One", Description="One", OrderNumber=1 },
    new ListViewTemplate { Name="Two", Description="Two", OrderNumber=2 },
    new ListViewTemplate { Name="Three", Description="Three", OrderNumber=3 }, new ListViewTemplate { Name="Four", Description="Four", OrderNumber=4 },
    new ListViewTemplate { Name="Five", Description="Five", OrderNumber=5 },
    };
    }
    }


    • Set page in to run the application

    public class App : Application
    {
    public App()
    {
    MainPage = new MainMaster();
    }

    }

    • Run the application