如何使用命令中的mvvm属性将picker值保存到webapi



我有一个xamarin表单应用程序,希望保存一些值​​我通过web api从picker那里得到的。目标是将此值以及其他属性保存在链接到sql server数据库的web api中,但我在如何通过mvvm引用选择器中选择的值方面存在问题。我可以从选择器加载数据,但我不知道如何保存这些值​​通过引用mvvm中的选择器。

UsuarioModel类这是模型类,它具有CodPerfil属性,该属性是应该存储在我的web api数据库中的外键,并且必须与将在选择器中选择的值相对应。

public class UsuarioModel
{
public int CodUsuario { get; set; }
public string Nome { get; set; }
public string Senha { get; set; }
public int Telefone { get; set; }
public DateTime DataRegisto { get; set; }
public bool Estado { get; set; }
public int CodPerfil { get; set; }
}

PerfilModel类

public class PerfilModel
{
public int CodPerfil { get; set; }
public string Titulo { get; set; }
}

Web API控制器插入数据

public IHttpActionResult Registo(UsuarioModel usuario)
{
connection();
SqlCommand cmd = new SqlCommand("SpAddNewUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Nome", usuario.Nome);
cmd.Parameters.AddWithValue("@Senha", usuario.Senha);
cmd.Parameters.AddWithValue("@Telefone", usuario.Telefone);
cmd.Parameters.AddWithValue("@CodPerfil", usuario.CodPerfil);
conn.Open();
cmd.ExecuteNonQuery();
return Ok();
}

Web API控制器为Xamarin中的选取器获取数据

public IEnumerable<PerfilModel> GetPerfisApp()
{
List<PerfilModel> perfilModels = new List<PerfilModel>();
connection();
SqlCommand cmd = new SqlCommand("SpGetPerfilApp", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
PerfilModel perfil = new PerfilModel();
perfil.CodPerfil = Convert.ToInt32(reader["CodPerfil"]);
perfil.Titulo = reader["Titulo"].ToString();
perfilModels.Add(perfil);
}
conn.Close();
return perfilModels;
}

ViewModel类

public class AddRegistoUsuarioViewModel : BaseViewModel
{
ApiServices _apiServices = new ApiServices();
string _nome;
public string Nome
{
get
{
return _nome;
}
set
{
if (value != null)
{
_nome = value;
OnPropertyChanged();
}
}
}
string _senha;
public string Senha
{
get
{
return _senha;
}
set
{
if (value != null)
{
_senha = value;
OnPropertyChanged();
}
}
}
int _telefone;
public int Telefone
{
get
{
return _telefone;
}
set
{
_telefone = value;
OnPropertyChanged();
}
}
int _codperfil;
public int CodPerfil
{
get
{
return _codperfil;
}
set
{
_codperfil = value;
OnPropertyChanged();
}
}
public string Message { get; set; }
public ICommand Registar
{
get
{
return new Command(async () =>
{
var usuario = new UsuarioModel
{
Nome = Nome,
Senha = Senha,
Telefone = Telefone,
CodPerfil = SelectedPerfil.CodPerfil
};
await _apiServices.RegistoUsuarioAsync(usuario);
});
}
}
public AddRegistoUsuarioViewModel()
{
GetPerfisApp();
}
public async void GetPerfisApp()
{
using (var client = new HttpClient())
{
var uri = "https://webapiigarbage-ff4.conveyor.cloud/api/Usuario/PerfisApp";
var result = await client.GetStringAsync(uri);
var PerfilList = JsonConvert.DeserializeObject<List<PerfilModel>>(result);
Perfis = new ObservableCollection<PerfilModel>(PerfilList);
}
}
PerfilModel _selectedPerfil;
public PerfilModel SelectedPerfil
{
get
{
return _selectedPerfil;
}
set
{
if (SelectedPerfil != value)
{
_selectedPerfil = value;
OnPropertyChanged();
}
}
}

ObservableCollection<PerfilModel> _perfis;
public ObservableCollection<PerfilModel> Perfis
{
get
{
return _perfis;
}
set
{
_perfis = value;
OnPropertyChanged();
}
}
}

API服务类我尝试使用以下表单:CodPerfil=SelectedPerfil.CodPerfil但我没有成功。

public async Task RegistoUsuarioAsync(UsuarioModel usuario)
{
var client = new HttpClient();
var json = JsonConvert.SerializeObject(usuario);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://mywebsite/api/Usuario/Registo", content);
}

RegisterPage.xaml.cs

public RegisterPage()
{
InitializeComponent();
BindingContext = new RegistoUsuarioViewModel();
}

RegisterPage.xaml


<Entry Placeholder="Nome de Usuário" 
x:Name="NomeEntry" />
<Picker x:Name="PerfilPicker" Title="Selecione o seu Perfil" FontSize="Large" HorizontalOptions="Center"
ItemsSource="{Binding Perfis}" 
ItemDisplayBinding="{Binding Titulo}" 
SelectedItem="{Binding SelectedPerfil}" />
<Entry Placeholder="Número de Telemóvel" 
x:Name="TelefoneEntry"
Keyboard="Telephone"/>
<Entry Placeholder="Senha" x:Name="SenhaEntry" IsPassword="True"/>
<Button Text="Registar"
TextColor="White" 
BackgroundColor="#07E3B0"
x:Name="ButtonLogin"
Command="{Binding Registar}"/>

如果有人能帮助我,我将不胜感激。

感谢您的提示。发生的情况是,在Register.xaml.cs类中绑定的视图模型不是包含Register命令的视图模型。我通过替换视图模型解决了这个"问题",它成功了!

RegisterPage.xaml.cs

public RegisterPage()
{
InitializeComponent();
BindingContext = new AddRegistoUsuarioViewModel();
}

最新更新