Search code examples
xamarinxamarin.formsmvvmxamarin.androidpicker

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


I have a xamarin forms application and would like to save some values ​​that I got from the picker via the web api. The objective is to save this value as well as the other properties in the web api that is linked to the sql server database, but I have issues in how to reference the value selected in the picker through mvvm. I can load the data from the picker but I just don't know how to save these values ​​by referencing the picker in mvvm.

UsuarioModel Class This is the model class, it has the CodPerfil property which is the foreign key that should be stored in my web api database and must correspond to the value that will be selected in the picker.

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 Controller to Insert Data

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 Controller to Get Data for Picker in 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 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 Service Class I tried to use this form: CodPerfil = SelectedPerfil.CodPerfil But I was not successful.

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}"/>

I would be grateful if someone could help me.


Solution

  • thanks for the tips. what happened was that the viewmodel that was being binded in the Register.xaml.cs class was not the one that contained the Register command. I solve the 'problem' by replacing the viewmodel and it worked!

    RegisterPage.xaml.cs

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