Building Quiz with Xamarin Forms and .netMaui?

255 views Asked by At

i'm making a quiz model for my application using .net maui and .net web api so first step i create a home page inside her i retrieved all my quizes the user than click on a quiz and i make a navigation to a quizdetails page that contain a start quiz button and i passed the quiz object as a parameter inside my naviagtion method so i can bind the properties of the quiz in my quizdetails page like the title etc.. so the problem is i try to get question by quiz when the user click on the start button but it does not work . i try to pass the id of that selected quiz from quizdetailsviewmodel to quizdisplay viewmodel by this navigation method :

 public async Task Navigation()
        {
            // Pass the selected quiz ID as a navigation parameter
            await Shell.Current.GoToAsync($"{nameof(QuizDisplay)}?quizId={QuizesVM.Id}");
          
        }

and inside my quizdisplayviewmodel i try to make this logic :

 [QueryProperty(nameof(QuizId), nameof(QuizId))]
    public partial class QuizDisplayViewModel : BaseViewModel
    {     
        public ObservableCollection<QuestionVM> QuestionsVM { get; } = new();
        QuizDisplayService quizDisplayService;
        private readonly IMapper _mapper;

        private bool isLoading;
        public bool IsLoading
        {
            get => isLoading;
            set => SetProperty(ref isLoading, value);
        }
        private int quizId;
        public int QuizId
        {
            get => quizId;
            set
            {
                quizId = value;
                GetQuizQuestionsAsync();
            }
        }
        //GetQuestions
        [RelayCommand]
        public async Task GetQuizQuestionsAsync()
        {
            if (IsBusy)
                return;
            try
            {
                IsLoading = true; // Show the loading animation
                IsBusy = true;

                var questions = await quizDisplayService.LoadQuizData(QuizId);

                if (QuestionsVM.Count != 0)
                {
                    QuestionsVM.Clear();
                }

                await Task.Delay(2000); // Add a 2-second delay

                foreach (var question in questions)
                {
                    QuestionsVM.Add(_mapper.Map<QuestionVM>(question));
                }
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error !!", $"Unable to get Quiz Questions: {e.Message}", "Ok");
            }
            finally
            {
                IsBusy = false;
                IsLoading = false;
            }
        }

        public QuizDisplayViewModel(QuizDisplayService quizDisplayService, IMapper _mapper)
        {
            this.quizDisplayService = quizDisplayService;
            this._mapper = _mapper;
        }
    }

also this is my quizdisplayservice code :

 public async Task<List<Question>> LoadQuizData(int quizId)
        {
            var response = await _httpClient.GetAsync($"{baseUrl}/GetQuestionsPerQuiz/{quizId}");
          
            if (!response.IsSuccessStatusCode)
            {
                // handle error
                return null;
            }
            var content = await response.Content.ReadAsStringAsync();
            var questions = JsonConvert.DeserializeObject<List<Question>>(content);
            return questions;
        }
    }

Can SomeOne Help me because i stacked the error is Unable Unable to get Quiz Questions

3

There are 3 answers

2
BoeykensBrooklyn On

At the moment I am also busy with an new application in .NET MAUI and I faced the same problem.

I have a mainpage with an collectionview of bikes. If you tap on a bike you go to a detailspage.

Tap recognizer code:

    private async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
   {
    var selectedBike = ((VisualElement)sender).BindingContext as Fietsmodel;

    if (selectedBike == null)
    {
        return;
    }

    await Shell.Current.GoToAsync(nameof(BikeInformationPage), true, new Dictionary<string, object>
    {
        {
            "SelectedBike",
            selectedBike
        },            {
            "User", _viewmodel.User
        }
    });
}

This is than my code in Viewmodel:

[QueryProperty(nameof(User), "User")]
[QueryProperty(nameof(SelectedFiets), "SelectedBike")]
public partial class BikeDetailsViewModel : BaseViewModel

Something you need to do is registering your routing so in AppShell.xaml.cs you add the page like this:

public AppShell()
{
    InitializeComponent();
    Routing.RegisterRoute(nameof(BikeInformationPage), typeof(BikeInformationPage));
}

I hope this will help you further

1
BuckBuchanan On

Have you tried using ObservableProperty yet?

Install the Maui Community Toolkit from Nuget, then you can change your VM code to something like this:

[ObservableProperty]
public int _quizId;

[ObservableProperty]
public string _quizQuestion;

public async Task GetQuizQuestionsAsync()
{
QuizId=123;
QuizQuestion = "My question text here";
}

Then on the page just display it by binding:

<Label Text={Binding QuizQuestion} />

0
BoeykensBrooklyn On

You can use the Community toolkit .MVVM en Community.Toolkit.Maui. In your Modelview you can do like this:

 [ObservableProperty]
 int quizId;

 [ObservableProperty]
 string quizQuestion;

In XAML you can use this:

 <ContentPage.Behaviors>
    <toolkit:EventToCommandBehavior EventName="LayoutChanged"
                                Command="{Binding GetQuizQuestionsAsyncCommand}" />
</ContentPage.Behaviors>

This works for me to get data on page load