0

I want to pass the data to another view page. So far I can get the data I need to pass. My problem is how do I pass the data in MVVM. I used Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true); When I add contactId inside DatabaseSyncPage() an error occurs. "The error is 'DatabaseSyncPage' does not contain a constructor that takes 1 arguments"

My code:

LoginPageViewModel.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.Data;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace TBSMobileApplication.ViewModel
{
    public class LoginPageViewModel : INotifyPropertyChanged
    {
        void OnProperyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string username;
        public string password;

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnProperyChanged(nameof(Username));
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnProperyChanged(nameof(Password));
            }
        }

        public class LoggedInUser
        {
            public string ContactID { get; set; }
        }

        public ICommand LoginCommand { get; set; }

        public LoginPageViewModel()
        {
            LoginCommand = new Command(OnLogin);
        }

        public void OnLogin()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                MessagingCenter.Send(this, "Login Alert", Username);
            }
            else
            {
                var current = Connectivity.NetworkAccess;

                if (current == NetworkAccess.Internet)
                {
                    var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
                    var request = HttpWebRequest.Create(string.Format(@link));
                    request.ContentType = "application/json";
                    request.Method = "GET";

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                var content = reader.ReadToEnd();

                                if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
                            {
                                MessagingCenter.Send(this, "Http", Username);
                            }
                            else
                            {
                                var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
                                var contactId = result[0].ContactID;
                                Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage { myId = contactId }, true);
                            }
                        }
                    }
                }
                else
                {
                    MessagingCenter.Send(this, "Not Connected", Username);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

DatabaseSyncPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TBSMobileApplication.View
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DatabaseSyncPage : ContentPage
    {
        public int myId { get; set; }

         public DatabaseSyncPage ()
         {
             InitializeComponent ();
             DisplayAlert("Message", Convert.ToString(myId), "ok");
         }
    }
}

3 Answers3

0

I'm assuming that contactID is an int.

Create an additional constructor in your DatabaseSyncPage:

public DatabaseSyncPage (int contactID)
{
    // TODO: Do something with your id
}

But this passes the data to the page, not the page model. Are you using any kind of framework? It would probably be worth looking into that.

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100
  • yes, ContactID is an int. How can I get the contactid from my viewmodel to databasesync page? –  Jul 26 '18 at 08:00
  • By adding this additional constructor to your `DatabaseSyncPage` :) – Gerald Versluis Jul 26 '18 at 08:08
  • i believe the answer to this question is widely available rather than asking questions here you should read some documentation or follow tutorials for Xamarin, here is the [link](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/) – Ronak Shetiya Jul 26 '18 at 09:25
0

If you want to send the int. First declare that in your DatabaseSyncPage Like below

public partial class DatabaseSyncPage : ContentPage
{
    public DatabaseSyncPage( int Id)
    {
    }
}

& when you are pushing your page in your code else block do like this

if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
    MessagingCenter.Send(this, "Http", Username);
}
else
{
    var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
    var contactId = result[0].ContactID;
    Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(contactId), true);
}
R15
  • 13,982
  • 14
  • 97
  • 173
  • How can I check if the data has been passed? –  Jul 26 '18 at 08:29
  • I have add DisplayAlert("Message", Convert.ToString(myId), "ok"); but no display message shows –  Jul 26 '18 at 08:32
  • I have edited my code I added alert on DatabaseSyncPage below initializecomponent –  Jul 26 '18 at 08:54
  • I am telling you to update LoginPageViewModel.cs class code. & remove Login.xaml & Login.xaml.cs page – R15 Jul 26 '18 at 09:03
  • Everything looks fine. Put breakpoint in your else condition where you are pushing page & 1 breakpoint in DatabaseSyncPage & check what value going & what coming. – R15 Jul 26 '18 at 09:12
  • the myId value is 0 –  Jul 26 '18 at 09:28
  • Whatever passing would be displaying in other page. There is nothing wrong with code. – R15 Jul 26 '18 at 09:35
  • when the breakdown starts at the other page it would go to the displayalert first the go to public int myId { get; set; } –  Jul 26 '18 at 09:44
  • Alert might not getting Id as it is constructor calling very first. But you can use Id in other overriden methods. – R15 Jul 26 '18 at 09:48
  • Can you update your code? so I can compare I think I am doing something wrong –  Jul 26 '18 at 09:49
  • See updated answer. I have modified code & try to debug to see value. – R15 Jul 26 '18 at 10:32
  • How can I get this over MVVM? –  Jul 26 '18 at 10:57
  • If you want to pass the data while pushing pages this way applicable for MVVM too. – R15 Jul 26 '18 at 10:59
  • Can I ask how? Sorry I really am new to xamarin and MVVM –  Jul 26 '18 at 11:00
  • Please help me convert this to mvvm –  Jul 27 '18 at 03:25
  • I really need your help –  Jul 27 '18 at 05:52
-1

You can use xamrin.plugins.settings nuget package.

Rajat Shelke
  • 39
  • 2
  • 3
  • The app settings should be used for persisted values such as server url's and first time launched, last checked dates. Not for passing data between views! – Axemasta Jul 26 '18 at 23:15
  • @Axemasta can you help my friend https://stackoverflow.com/questions/51549737/xamarin-passing-and-checking-data-to-other-view-using-mvvm –  Jul 27 '18 at 02:39