Xamarin使用REST API中的显示列表 [英] Show List in Xamarin consuming REST API

查看:33
本文介绍了Xamarin使用REST API中的显示列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后我创建一个名为ApiServices的服务,该服务使用API​​:

APISERVICE.CS:

 公共异步任务< Response>GetList< T>(字符串urlBase,字符串servicePrefix,字符串控制器){尝试{var client = new HttpClient();client.BaseAddress =新的Uri(urlBase);var url = string.Format("{0} {1}",servicePrefix,controller);var response =等待client.GetAsync(url);var result = await response.Content.ReadAsStringAsync();如果(!response.IsSuccessStatusCode){返回新的回应{IsSuccess = false,讯息=结果,};}var list = JsonConvert.DeserializeObject< List< T>>(结果);返回新的回应{IsSuccess = true,留言 = "好的",结果=清单,};}抓住(前例外){返回新的回应{IsSuccess = false,Message = ex.Message,};}} 

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

PRODUCTOSVIEWMODEL.CS:

  public ObservableCollection< Product>Productos {get {return this.productos;}设置{this.SetValue(ref this.productos,value);}}私有ObservableCollection< Product>产品;私有ApiService apiService;公共ProductosViewModel(){this.apiService = new ApiService();this.LoadProductos();}私有异步void LoadProductos(){var response =等待this.apiService.GetList< Product>("https://salesapiservices.azurewebsites.net","/api","/Products");如果(!response.IsSuccess){await Application.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar");返回;}var list =(List< Product>)response.Result;Productos =新的ObservableCollection< Product>(列表);} 

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

 < 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}}"标题="Productos">< ContentPage.Content>< StackLayoutBindingContext ="{Binding Productos}"填充="4"><列表视图ItemsSource ="{Binding Productos}"></ListView></StackLayout></ContentPage.Content></ContentPage> 

我附上我的产品型号:

 公共类产品{public int ProductId {get;放;}公共字符串说明{放;}公共字符串备注{get;放;}公共字符串ImagePath {get;放;}公共十进制价格放;}公共布尔IsAvailable {get;放;}公开的DateTime PublishOn {放;}公共字符串ImageFullPath{得到{如果(string.IsNullOrEmpty(this.ImagePath)){返回无产品";}返回$"https://salesbackend.azurewebsites.net/{this.ImagePath.Substring(1)}";}}公共重写字符串ToString(){返回this.Description;}} 

我验证JSON是否到达:

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

对我有什么帮助吗?请随时关注您的评论

解决方案

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

您可以参考以下代码:

 < ListView ItemsSource ="{Binding Productos}">< ListView.ItemTemplate>< DataTemplate>< ViewCell><标签文本="{绑定说明}"FontSize ="Large"FontAttributes =粗体"Horizo​​ntalTextAlignment =开始"Margin ="20,0,0,0"VerticalTextAlignment ="Center"></ViewCell></DataTemplate></ListView.ItemTemplate></ListView> 

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:

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>

这篇关于Xamarin使用REST API中的显示列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆