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,,
- <StackLayout BackgroundColor="White">
- <WebView x:Name="articleweb" VerticalOptions="FillAndExpand">
- </WebView>
- </StackLayout>
After that open this code behind page and write the following code as below,
- using Newtonsoft.Json;
- using System;
- using System.Net.Http;
- using Xamarin.Forms;
- namespace Testapp
- {
- public partial class DetailsPage: ContentPage
- {
- public class Detail
- {
- public string ArticleDetail
- {
- get;
- set;
- }
- }
- public DetailsPage()
- {
- InitializeComponent();
- GetDetail(Enter id);
- }
- public async void GetDetail(string id)
- {
- HttpClient client = new HttpClient();
- var RestURL = Your api url.
- client.BaseAddress = new Uri(RestURL);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = await client.GetAsync(RestURL);
- HttpContent _Hcontent = response.Content;
- var result = await _Hcontent.ReadAsStringAsync();
- var Items = JsonConvert.DeserializeObject < Detail > (result);
- articleweb.Source = new HtmlWebViewSource
- {
- Html = Items.ArticleDetail;
- };
- }
- }
- }
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: