Bind HTML Data Into WebView Using Xamarin Forms

We will discuss how to bind data in HTML-formatted strings in WebView with Xamarin Forms. First create Forms Xaml Page in Portable project shown on top right-hand-side of Solution. Open this Forms Xaml Page and write the following code,, 
  1. <StackLayout BackgroundColor="White">  
  2. <WebView x:Name="articleweb" VerticalOptions="FillAndExpand">  
  3. </WebView>  
  4. </StackLayout>  
After that open this code behind page and write the following code as below,
  1. using Newtonsoft.Json;  
  2. using System;  
  3. using System.Net.Http;  
  4. using Xamarin.Forms;  
  5. namespace Testapp  
  6. {  
  7.     public partial class DetailsPage: ContentPage   
  8.     {  
  9.         public class Detail   
  10.         {  
  11.             public string ArticleDetail   
  12.             {  
  13.                 get;  
  14.                 set;  
  15.             }  
  16.         }  
  17.         public DetailsPage()   
  18.         {  
  19.             InitializeComponent();  
  20.             GetDetail(Enter id);  
  21.         }  
  22.         public async void GetDetail(string id)   
  23.         {  
  24.             HttpClient client = new HttpClient();  
  25.             var RestURL = Your api url.  
  26.             client.BaseAddress = new Uri(RestURL);  
  27.             client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));  
  28.             HttpResponseMessage response = await client.GetAsync(RestURL);  
  29.             HttpContent _Hcontent = response.Content;  
  30.             var result = await _Hcontent.ReadAsStringAsync();  
  31.             var Items = JsonConvert.DeserializeObject < Detail > (result);  
  32.             articleweb.Source = new HtmlWebViewSource   
  33.             {  
  34.                 Html = Items.ArticleDetail;  
  35.             };  
  36.         }  
  37.     }  
  38. }   
Above code fetches records from Web API in JSON format and stores these records in item variable. This will show data in HTML-formatted string in WebView.
 
Finally, build your project and when build is successful then run the project. You can see result in different platforms like Android, iOS, Windows phone as shown in figure 1.
 
 
 
Summary
 
In this article we discussed how to bind data in HTML-formatted string in WebView with Xamarin Forms. I hope you enjoyed this article.
 
You can read more of my articles related to Xamarin here:

Up Next
    Ebook Download
    View all
    Learn
    View all