locked
how to use two models in mvvm constructor with ID to fetch data ? RRS feed

  • Question

  • User389299 posted

    in my xamarin forms project, i have two models. the first model contains the information relating to a document (ID, Title, number, date, description), and the second model *contains the types of documents (Id, type of document).* When entering information on the form, the second model is used as a spinner which displays the document types. what i want is to be able to save the type of document selected in the sqlite database and be able to retrieve it in the info update interface**

    Wednesday, December 18, 2019 10:29 AM

All replies

  • User382871 posted

    When entering information on the form, the second model is used as a spinner which displays the document types. This is similar to selecting a city and region. Wrap the model class to a collection in another model.

    Check the code: Page.xaml.cs ``` public MainPage() { InitializeComponent();

    _ViewModel viewModel = new _ViewModel()
    { 
        collection = new ObservableCollection<Model_2>()
        {
            new Model_2() { ID = 1, Title = "Title_1", models = { new Model_1 { Type = "Type_1" } ...} },
            ...
        }
    };
    
    BindingContext = viewModel;
    

    } Model_1 class public class Model1 { public string Type { get; set; } } Model_2 class public class Model2 { public int ID{ get; set; } public string Title{ get; set; } public ObservableCollection models{ set; get; } public Model_2() { models= new ObservableCollection(); } } ViewModel class public class _ViewModel { public ObservableCollection collection{ get; set; }

    public _ViewModel()
    {
        collection= new ObservableCollection<Model_2>();
    }
    

    } ```

    Wednesday, December 18, 2019 12:34 PM
  • User389299 posted

    i have a bugs

    Wednesday, December 18, 2019 7:00 PM
  • User382871 posted

    If you are facing some issues while implementing, try to post the particular error with the corresponding codes here.

    Thursday, December 19, 2019 7:53 AM
  • User76049 posted

    @mrlenoir said: i have a bugs

    https://forums.xamarin.com/discussion/87290/xamarin-forum-rules-and-guidelines#latest

    if you want help, please follow these guidelines. "I have bugs" helps no one trying to assist you.

    Thursday, December 19, 2019 9:18 AM
  • User389299 posted

    @NMackay Right

    Thursday, December 19, 2019 9:27 AM
  • User389299 posted

    @NMackay Can you help me please ?

    Thursday, December 19, 2019 9:32 AM
  • User76049 posted

    @mrlenoir said: @NMackay Can you help me please ?

    @Jarvan is already assisting you, follow his guidance and provide more information

    If you are facing some issues while implementing, try to post the particular error with the corresponding codes here.

    Thursday, December 19, 2019 9:34 AM
  • User389299 posted

    I tried @Jarvan's solution. But it doesn't work. I tell myself that he may have misunderstood my problem. is it possible to publish part of my code in this forum to help you see more clearly ??

    Thursday, December 19, 2019 9:39 AM
  • User76049 posted

    @mrlenoir said: I tried @Jarvan's solution. But it doesn't work. I tell myself that he may have misunderstood my problem. is it possible to publish part of my code in this forum to help you see more clearly ??

    Yes, use markdown and wrap your snipet in the three ` on either side of the code block. If it's a project, post the code to github for a solution of maybe pastebin and post the link here. You can also attach a rar file of your solution to a response but there is an attachment limit (10mb I think)

    Thursday, December 19, 2019 11:17 AM
  • User389299 posted

    ** [Table("Document")] public partial class Document {

        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
    
        public int? Doc_id { get; set; }
    
    
        [MaxLength(50)]
        public string nomDocument { get; set; }
    
    
        [MaxLength(50)]
        public string Code { get; set; }
    
        public bool? Periodicite { get; set; }
    
        [MaxLength(254)]
        public string DescriptionDocument { get; set; }
    
        public DateTime? DateEts { get; set; }
    
        public DateTime? DateExp { get; set; }
    
        [MaxLength(70)]
        public string Organisme { get; set; }
    
        public DateTime? DateEnr { get; set; } = DateTime.Now;
    
        public DateTime? DateDerModif { get; set; }
    
        [MaxLength(50)]
        public string TypeEnr { get; set; }
    
        public byte[] Fichier { get; set; }
        public string NomduFichier { get; set; }
        public string AccesFichier { get; set; }
    
        public int? IdTypeDoc { get; set; }
    
        public int? IdEvenement { get; set; }
    
    }
    

    =====================================

    [Table("TypeDocument")] public partial class TypeDocument {

          [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
    
    
        [MaxLength(30)]
        public string NomTypeDcocument { get; set; }
    

    }

    public class BaseDocumentViewModel : ViewModelDeBase { public Document _document; public TypeDocument _typeDocument;

        public INavigation _navigation;
        public IValidator _documentValidator;
    
    
    
        public string nomDocument
        {
            get => _document.nomDocument;
    
            set
            {
                _document.nomDocument = value;
                NotifyPropertyChanged("nomDocument");
            }
        }
    
    
    
    
        public List<TypeDocument> TypedocumentList
        {
            get;
            set;
        }
    
    
        public string NomTypeDcocument
        {
            get => _typeDocument.NomTypeDcocument;
            set
            {
                _typeDocument.NomTypeDcocument = value;
                NotifyPropertyChanged("NomTypeDcocument");
            }
        }
    
    
    
    
        TypeDocument _selectedItemPicker;
        public TypeDocument SelectedItemPicker
        {
            get
            {
                return _selectedItemPicker;
            }
    
            set
            {
                if (_selectedItemPicker != value)
                {
                    _selectedItemPicker = value;
                    NotifyPropertyChanged("SelectedItemPicker");
                }
            }
        }
    
    
    
        /// <summary>
        /// fin des infos de typeDocument
        /// </summary>
    
    
        public string Code
        {
            get => _document.Code;
            set
            {
                _document.Code = value;
                NotifyPropertyChanged("Code");
            }
        }
    
    
        public bool? Periodicite
        {
            get => _document.Periodicite;
            set
            {
                _document.Periodicite = value;
                NotifyPropertyChanged("Periodicite");
            }
        }
    
    
        public string DescriptionDocument
        {
            get => _document.DescriptionDocument;
            set
            {
                _document.DescriptionDocument = value;
                NotifyPropertyChanged("Description");
            }
        }
    
        public DateTime? DateEts
        {
            get => _document.DateEts;
            set
            {
                _document.DateEts = value;
                NotifyPropertyChanged("DateEts");
            }
        }
    
        public DateTime? DateExp
        {
            get => _document.DateExp;
            set
            {
                _document.DateExp = value;
                NotifyPropertyChanged("DateExp");
            }
        }
    
        public string Organisme
        {
            get => _document.Organisme;
            set
            {
                _document.Organisme = value;
                NotifyPropertyChanged("Organisme");
            }
        }
    
    
    
    
    
        public byte[] Fichier
        {
            get => _document.Fichier;
            set
            {
                _document.Fichier = value;
                NotifyPropertyChanged("Fichier");
            }
        }
    
        public string NomduFichier
        {
            get => _document.NomduFichier;
            set
            {
                _document.NomduFichier = value;
                NotifyPropertyChanged("NomduFichier");
            }
        }
    
        public string AccesFichier
        {
            get => _document.AccesFichier;
            set
            {
                _document.AccesFichier = value;
                NotifyPropertyChanged("AccesFichier");
            }
        }
    
    
    
        List<Document> _documentList;
        public List<Document> DocumentList
        {
            get
            {
                List<Document> theCollection = new List<Document>();
    
                if (_documentList != null)
                {
                    List<Document> entities = (from e in _documentList
                                               where e.nomDocument.Contains(_searchText)
                                               select e).ToList<Document>();
                    if (entities != null && entities.Any())
                    {
                        theCollection = new List<Document>(entities);
                    }
                    else
                    {
    
                    }
                }
    
                return theCollection;
            }
            set
            {
                _documentList = value;
                NotifyPropertyChanged("DocumentList");
            }
        }
    
    
    
        private string _searchText = string.Empty;
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value) { _searchText = value ?? string.Empty; NotifyPropertyChanged("SearchText"); }
    
                if (SearchCommand.CanExecute(null))
                {
                    SearchCommand.Execute(null);
                }
            }
        }
    
    
    
        private Command _searchCommand;
        public ICommand SearchCommand
        {
            get
            {
                _searchCommand = _searchCommand ?? new Command(DoSearchCommand, CanExecuteSearchCommand);
                return _searchCommand;
            }
        }
        private void DoSearchCommand()
        {
            // Refresh the list, which will automatically apply the search text
            NotifyPropertyChanged("DocumentList");
        }
        private bool CanExecuteSearchCommand()
        {
            return true;
        }
    
    
    }
    

    }

    ==============================================

    public class EnregistrementDocumentViewModel : BaseDocumentViewModel
    {
        public ICommand EnregistrementCommand { get; private set; }
        public ICommand AnnulerCommand { get; private set; }
        public ICommand AjouterDocument { get; private set; }
    
    
    
        public EnregistrementDocumentViewModel(INavigation navigation)
        {
            _navigation = navigation;
            _document = new Document();
            _typeDocument = new TypeDocument();
            _documentValidator = new DocumentValidator();
    
    
            AjouterDocument = new Command(async () => await AjoutDocDuDocument());
    
            EnregistrementCommand = new Command(async () => await EnregistrementDuDocument());
            AnnulerCommand = new Command(async () => await Annuler());
    
            FetchTypeDocument();
    
        }
    
    
    
    
        private async Task AjoutDocDuDocument()
        {
            try
            {
    
    
                var fileData = await CrossFilePicker.Current.PickFile();
    
                if (fileData != null)
                {
    
                    NomduFichier = fileData.FileName;
                    AccesFichier = fileData.FilePath;
                    Fichier = fileData.DataArray;
    
    
                }
    
    
            }
            catch (Exception ex)
            {
                NomduFichier = ex.ToString();
    
            }
    
    
        }
    
    
        /// <summary>
        /// Afficher la liste des type de document dans le picker
        /// </summary>
        /// <returns></returns>
    
        async Task FetchTypeDocument()
        {
            TypedocumentList = await new DatabaseHelper().TousLesTypesDocumentsAsync();
        }
    
    
    
    
        /// <summary>
        /// Enregistrer les documents utilisateur
        /// </summary>
        /// <returns></returns>
    
        async Task EnregistrementDuDocument()
        {
            var validation = _documentValidator.Validate(_document);
    
        if (validation.IsValid)
            {
    
              bool isUserAccept = await Application.Current.MainPage.DisplayAlert(Messages.MessageEnregistrement, Messages.MessageValidation, "Enregistrer", "Annuler") ;
    
            if (isUserAccept)
            {
                    _document.EnregistrerEnBase();
                    _typeDocument.EnregistrerEnBase();
    
                    var ldoc = new DatabaseHelper().TousLesDocuments().GetAwaiter().GetResult();
                    var doc = ldoc.FindLast(p=>p.nomDocument!= null);
    
    
                    if (App.MembreActuel==null)
                    {
                        App.MembreActuel = App.user;
    
                    }
    
                    App.MembreActuel.AttribuerDocument(doc);
    
                    await Application.Current.MainPage.DisplayAlert(Messages.MessageSucces, Messages.MessageOk, "OK");
    
    
                await PopupNavigation.Instance.PopAsync();
                    MessagingCenter.Send<App>((App)Application.Current, "ActualiserListe");
    
    
                }
            }
         else
              {
                  await Application.Current.MainPage.DisplayAlert(Messages.MessageTitleError, validation.Errors[0].ErrorMessage, "Ok");
                }
    
            }
    
    
        /// <summary>
        /// Annuler la procedure enregistrement
        /// </summary>
        /// <returns></returns>
    
        async Task Annuler()
        {
            await PopupNavigation.Instance.PopAsync();
        }
    
    
    }
    

    Thursday, December 19, 2019 11:41 AM
  • User389299 posted

    my problem is more at the level of the selector. the "SelectedItemPicker" variables. when I select an element in document type, the "SelectedItemPicker" returns me a null value. it does not record anything in the database.

    Thursday, December 19, 2019 11:44 AM
  • User382871 posted

    when I select an element in document type, the "SelectedItemPicker" returns me a null value. Here is the tutorial and sample code about CrossFilePicker plugin, you can refer to it. https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows

    Friday, December 20, 2019 3:02 PM