我在服务器上托管了一个WEB API,那里有一个带有名称和描述的Products表。我已经检查过邮递员了,可以了,当我尝试通过Visual Studio在xamarin中实现该方法时,通过其名称记录并显示在我不能的列表视图中。有人可以在代码中帮助我
private async void GetProductByName(string Name)
{
using (var client = new HttpClient())
{
txtTest.Text = "http://www.ProdutosAPITest6.hostname.com/api/products";
var URI = txtTest.Text + "/" + Name.ToString();
var response = await client.GetAsync(URI);
string products = await response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<Produto>(products);
listview.ItemsSource = products;
}
}
<ListView x:Name="ProductsList" ItemSelected="listaProducts_ItemSelected"
BackgroundColor="Aqua" SeparatorColor="Blue">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10,10" Orientation="Horizontal">
<Label Text="{Binding Id}" HorizontalOptions="StartAndExpand"/>
<Label Text="{Binding Name}" TextColor="Blue" HorizontalOptions="Center"/>
<Label Text="{Binding Description}" HorizontalOptions="End"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 0 :(得分:0)
我对您的代码做了一些编辑。
public async void GetProductByName(string Name)
{
var handler = new NativeMessageHandler();
var client = new HttpClient(handler);
client.Timeout = TimeSpan.FromSeconds(120);
txtTest.Text = "http://www.ProdutosAPITest6.hostname.com/api/products";
var URI = txtTest.Text + "/" + Name.ToString();
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(URI)
};
var response = await client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode == true)
{
var products = await response.Content.ReadAsStringAsync();
var resultModel = JsonConvert.DeserializeObject<Produto>(products);
return resultModel;
}
}
public ListView myListView { get { return ProductsList; } }
protected override async void OnAppearing()
{
var name = //pass name;
List<ProductModel> products = await GetProductByName(name);
if (products.Count() > 0)
{
myListView.ItemsSource = products;
}
base.OnAppearing();
}
我希望这对您有帮助