美好的一天。我只是一個新手在使用Xamarin.Forms,所以人們請幫助我。我創建了基本的移動應用程序。我還創建了一個ASP.NET WEB應用程序,使我能夠對員工姓名和部門進行CRUD記錄。我想要做的是獲得我在網站上創建的所有記錄並將其顯示給我的移動應用程序。但是我在將XAMARIN.FORMS連接到WEB SERVICE時遇到了問題。我能夠將記錄保存在WEB應用程序中,但是當我嘗試將它連接到我的移動應用程序時,它不起作用。這是一個跨平臺,但我首先關注Android版本,所以現在請忽略iOS和Windows。請幫幫我。如果我在這樣做的過程中走錯了路,或者如果您有其他想法,請讓我知道。 我希望我的代碼能幫上忙。非常感謝。如何將Xamarin.Forms移動應用程序正確連接到Web服務?
MainPageMain.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDemo.Views.MainPageMain"
xmlns:ViewModels="clr-namespace:XamarinDemo.ViewModels;assembly=XamarinDemo"
BackgroundColor="Teal">
<ContentPage.BindingContext>
<ViewModels:MainViewModel/>
</ContentPage.BindingContext>
<ListView ItemsSource="{Binding EmployeesList}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical"
Padding="12,6">
<Label Text="{Binding Name}"
FontSize="24"/>
<Label Text="{Binding Department}"
FontSize="18"
Opacity="0.6"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
MainViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.Services;
namespace XamarinFormsDemo.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
private List<Employee> _employeesList;
public List<Employee> EmployeesList
{
get { return _employeesList; }
set
{
_employeesList = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
InitializeDataAsync();
}
private async Task InitializeDataAsync()
{
var employeesServices = new EmployeesServices();
EmployeesList = await employeesServices.GetEmployeesAsync();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
EmployeesServices.cs
using Plugin.RestClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;
namespace XamarinFormsDemo.Services
{
public class EmployeesServices
{
public async Task<List<Employee>> GetEmployeesAsync()
{
RestClient<Employee> restClient = new RestClient<Employee>();
var employeesList = await restClient.GetAsync();
return employeesList;
}
}
}
您需要執行一些基本的調試以確定問題出在哪裏。你有沒有嘗試過?您似乎重複發佈完全相同的問題,但沒有任何新的信息可以幫助我們。例如,在您的GetEmployeeAsync()中添加一個簡單的Debug.Writeline(employeeList.Count())會告訴您您的服務是否正在向客戶端返回數據。 – Jason
你可以請教我如何做你說的先生調試的東西? –
你允許在Android的Manifest文件中允許訪問互聯網嗎?示例在這裏,https://developer.xamarin.com/recipes/android/general/projects/add_permissions_to_android_manifest/ – Bearcat9425