简体   繁体   中英

Show List in Xamarin consuming REST API

I want to show a list of products in Xamarin (VS 2017) consuming an API, but when running my app, it shows me an empty list (as seen in the image)

截图

for the above I verify through POSTMAN that the service is available to consume

邮差

then I create a service called ApiServices which consumes the API:

APISERVICE.CS:

public async Task<Response> GetList<T>(string urlBase, string servicePrefix, string controller)
        {
            try
            {
                var client = new HttpClient();          
                client.BaseAddress = new Uri(urlBase);
                var url = string.Format("{0}{1}", servicePrefix, controller);
                var response = await client.GetAsync(url);
                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = result,
                    };
                }

                var list = JsonConvert.DeserializeObject<List<T>>(result);

                return new Response
                {
                    IsSuccess = true,
                    Message = "Ok",
                    Result = list,
                };
            }
            catch (Exception ex)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                };
            }
        }

then, in my ProductsViewModel, I call the GetList method and I pass the parameters:

PRODUCTOSVIEWMODEL.CS:

public ObservableCollection<Product> Productos { get { return this.productos;  }
                                                           set { this.SetValue(ref this.productos, value); }
                                                         }    
        private ObservableCollection<Product> productos;    
        private ApiService apiService;

        public ProductosViewModel()
        {
            this.apiService = new ApiService();
            this.LoadProductos();
        }

        private async void LoadProductos()
        {
            var response = await this.apiService.GetList<Product>("https://salesapiservices.azurewebsites.net", "/api", "/Products");

            if (!response.IsSuccess)
            {
                await Application.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar");
                return;
            }

            var list = (List<Product>)response.Result;              
            Productos = new ObservableCollection<Product>(list);
        }

finally, in my view I show what I want with the element:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Fundamentos.Views.ProductosPage"
             BindingContext="{Binding Main, Source={StaticResource Locator}}"
             Title="Productos">

    <ContentPage.Content>
        <StackLayout
            BindingContext="{Binding Productos}"
            Padding="4">

            <ListView 
                ItemsSource="{Binding Productos}">                    
            </ListView>

        </StackLayout>
    </ContentPage.Content>

</ContentPage>

I attach my Product Model:

public class Product
    {
        public int ProductId { get; set; }

        public string Description { get; set; }

        public string Remarks { get; set; }

        public string ImagePath { get; set; }

        public Decimal Price { get; set; }

        public bool IsAvailable { get; set; }

        public DateTime PublishOn { get; set; }

        public string ImageFullPath
        {
            get
            {
                if (string.IsNullOrEmpty(this.ImagePath))
                {
                    return "noproduct";
                }

                return $"https://salesbackend.azurewebsites.net/{this.ImagePath.Substring(1)}";
            }

        }

        public override string ToString()
        {
            return this.Description;
        }
    }

I verify that the JSON arrives:

JSON

It is worth mentioning that I am occupying the MVVM pattern and I have instantiated the ProductsViewModel class in the MainViewModel, and I have reviewed the code and I can not find the error!

any help for me? Stay tuned to your comments

As the model you are binding to your ListView is a complex type, you need to define a custom layout for your ListView

You can refer below code:

<ListView ItemsSource="{Binding Productos}"> 
<ListView.ItemTemplate>
   <DataTemplate>
      <ViewCell>
              <Label Text="{Binding Description}"
                FontSize="Large" 
                FontAttributes="Bold" 
                HorizontalTextAlignment="Start"
                Margin="20,0,0,0"
                VerticalTextAlignment="Center"
                >
    </ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>
</ListView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM