繁体   English   中英

Xamarin使用REST API中的显示列表

[英]Show List in Xamarin consuming REST API

我想显示使用API​​的Xamarin(VS 2017)中的产品列表,但是在运行我的应用程序时,它向我显示了一个空列表(如图中所示)

截图

对于上述情况,我通过POSTMAN验证了该服务可供使用

邮差

然后创建一个名为ApiServices的服务,该服务使用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,
                };
            }
        }

然后,在我的ProductsViewModel中,我调用GetList方法并传递参数:

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);
        }

最后,在我看来,我展示了我想要的元素:

<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>

我附上我的产品型号:

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;
        }
    }

我验证JSON是否到达:

JSON

值得一提的是,我正在使用MVVM模式,并且已经在MainViewModel中实例化了ProductsViewModel类,并且已经查看了代码,但找不到错误!

对我有帮助吗? 请继续关注您的评论

由于要绑定到ListView的模型是复杂类型,因此需要为ListView定义自定义布局

您可以参考以下代码:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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