如何使用命令中的 mvvm 属性将选择器值保存到网络 api?

how to save a picker value to the web api using the mvvm properties in the command?

我有一个 xamarin 表单应用程序,想保存一些我通过网络从选择器中获得的值 api。 objective 用于保存此值以及链接到 sql 服务器数据库的 Web api 中的其他属性,但我在如何引用中选择的值方面遇到问题通过 mvvm 选择器。我可以从picker加载数据但是我就是不知道如何通过在mvvm中引用picker来保存这些值。

UsuarioModel Class 这是模型 class,它有 CodPerfil 属性,这是应该存储在我的网络 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 Class

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;
        }

视图模型Class

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 服务 Class 我尝试使用这种形式: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 class 中绑定的视图模型不是包含 Register 命令的视图模型。我通过替换视图模型解决了 'problem',它成功了!

RegisterPage.xaml.cs

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