[英]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) 我想显示使用API的Xamarin(VS 2017)中的产品列表,但是在运行我的应用程序时,它向我显示了一个空列表(如图中所示)
for the above I verify through POSTMAN that the service is available to consume 对于上述情况,我通过POSTMAN验证了该服务可供使用
then I create a service called ApiServices which consumes the API: 然后创建一个名为ApiServices的服务,该服务使用API:
APISERVICE.CS: 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: 然后,在我的ProductsViewModel中,我调用GetList方法并传递参数:
PRODUCTOSVIEWMODEL.CS: 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! 值得一提的是,我正在使用MVVM模式,并且已经在MainViewModel中实例化了ProductsViewModel类,并且已经查看了代码,但找不到错误!
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
由于要绑定到
ListView
的模型是复杂类型,因此需要为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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.