How to display Image Data on .NET MAUI Blazor App

Maui Learner 500 Reputation points
2024-05-11T14:40:39.1366667+00:00

How to display Image Data on .NET MAUI Blazor App

Here is the api that fetches Image data

https://quizapijwt.azurewebsites.net/api/Questions

Images are stored in imagedata bytea

CREATE TABLE public."Questions" (

"SNo" int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY( INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START 1 CACHE 1 NO CYCLE),

"No" int4 NOT NULL,

"Topic" varchar(500) NULL,

"QuestionTitle" varchar(500) NULL,

"Opt1" varchar(50) NULL,

"Opt2" varchar(50) NULL,

"Opt3" varchar(50) NULL,

"Opt4" varchar(50) NULL,

"Answer" varchar(50) NULL,

"Time" int4 NULL,

"Correct" int4 NULL,

solution varchar(500) NULL,

imagedata bytea NULL,

CONSTRAINT pk_no PRIMARY KEY ("SNo")

);

  public class QuestionI
{
   
    public int SNo { get; set; }
    public int No { get; set; }
    public string Topic { get; set; }
    public string QuestionTitle { get; set; }
    public string Opt1 { get; set; }
    public string Opt2 { get; set; }
    public string Opt3 { get; set; }
    public string Opt4 { get; set; }
    public string Answer { get; set; }
    public int Time { get; set; }
    public int Correct { get; set; }
    public string Solution { get; set; }
    public byte[] Imagedata { get; set; }
    internal IEnumerable<Question> Select(Func<object, Question> value)
    {
        throw new NotImplementedException();
    }
}
@using System.Text;
@using System.Net.Http.Headers;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
@using System.Timers;
@using MauiAppMCQs.Models;
@page "/ImageApp"
<PageTitle>QuizApp</PageTitle>
@if (Questions.ToList().Count <= 0)
{
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
}
@if (Questions.ToList().Count > 0)
{
<button class="btn btn-primary" @onclick="NextQuestion">Next Question</button>
}
<p role="status">@Topich</p>
<p role="status">@Topic</p>
@if (Questions.ToList().Count > 0)
{
@number
@filler
@maxnumber
}
<p role="status">@QuestionTitleh</p>
<p role="status">@QuestionTitle</p>
<p role="status">@Answerh</p>
<p role="status">@Answer</p>
<p>@ImageData</p>
@if (Questions.ToList().Count > 0)
{
<p role="status">@timeh</p>
<p role="status">@time</p>
<button class="btn btn-primary" @onclick="ToggleAnswer">@buttonText</button>
<p style="display:@display">@solutionh</p>
<p style="display:@display">@solution</p>
<p>@(_currentCount)</p>
}
<p role="status">@errormessage</p>
@code {
public byte[] ImageData;
//   using Communication = Microsoft.Maui.ApplicationModel.Communication;
private string activity = "";
public string code; public string errortoggle = ""; public string errormessage = ""; public string checkflag = "N";
public string matches;
public int number;
public List<QuestionI> Questions { get; set; } = new List<QuestionI>();
protected int questionIndex = 0;
protected int score = 0;
protected int failedIndex = 0;
protected string[] failedQuestions = new string[500];
public int totaltime; public int totalquestions;
public int _currentCount = 0; public int _currentSec ;
private System.Timers.Timer _timer;
public int maxnumber; public int minumber; public string solution; public string Topic; public string QuestionTitle;
public string Answer;public int time; public string timeh;
bool isInitialized = false;
string solutionh;
string Topich;
string QuestionTitleh;
string Answerh;
List<QuestionI> res;
private string display = "none";
private string buttonText = "Hide Solution";
public int range;
string filler = "/";
private void ToggleAnswer()
{
    string bypass = "N";
    if (_currentCount > 60 )
    {
        bypass = "Y";
        errormessage = "";
    }
    else
    { errormessage = "Cannot Show Solution until 1 minute "; }
    if (bypass == "Y")
    {
        if (display == "none")
        {
            display = "block";
            buttonText = "Hide Solution";
        }
        else
        {
            checkflag = "Y";
            display = "none";
            buttonText = "Show Solution";
        }
    }
}
private void NextQuestion()
{
    if (checkflag == "N")
    { errormessage = "Show/Hide Solution to move to next question"; }
    else
    {
        _currentCount = 0;
        _timer = new();
        _timer.Interval = 1000;
        _timer.Elapsed += async (object? sender, ElapsedEventArgs e) =>
        {
            _currentCount++;
            await InvokeAsync(StateHasChanged);
        };
        _timer.Enabled = true;
        LoadQuestionsAsync();
        checkflag = "N";
        errormessage = " ";
    }
}
private void IncrementCount()
{
    _currentCount = 0;
    _timer = new();
    _timer.Interval = 1000;
    _timer.Elapsed += async (object? sender, ElapsedEventArgs e) =>
    {
        _currentCount++;
        _currentSec = _currentCount / 10;
        await InvokeAsync(StateHasChanged);
    };
    _timer.Enabled = true;
    LoadQuestionsAsync();
}
async Task<List<QuestionI>> GetApiData()
{
    string jwlurl="https://quizapijwt.azurewebsites.net/api/";
    List<QuestionI> Questions = new List<QuestionI>();
    string connected = "N";
    string apiUrl="https://quizapijwt.azurewebsites.net/api/";
    using (HttpClient client = new HttpClient())
    {
        try
        {
            // Make a GET request to the API
            //    HttpResponseMessage response = await client.GetAsync(apiUrl);
            client.BaseAddress = new Uri(apiUrl);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = null;
            response = await client.GetAsync("Questions");
            // Check if the request was successful (status code 200)
            if (response.IsSuccessStatusCode)
            {
                // Make a GET request to the API
                connected = "Y";
                // Read the content of the response
                string jsonString = await response.Content.ReadAsStringAsync();
                // Deserialize the JSON string into an object
                Questions = JsonConvert.DeserializeObject<List<QuestionI>>(jsonString);
                // truncate sqlLIte table Load sqlite table  from  Questions
                //If the first time when you load the api data, it will push data to the sqlite DB.
                //comment begins
                //   }
                //comment ends
            }
            else
            { // Load  Questions from sql lite  table
            }
        }
        catch (Exception ex)
        {
            if (connected == "N")
            {
            }
        }
    }
    return Questions;
}
private async Task LoadQuestionsAsync()
{
    display = "none";
    buttonText = "Show Solution";
    if (!isInitialized)
    {
        res = await GetApiData();
        Questions.AddRange(res.Select(r => new QuestionI
            {
                SNo = r.No,
                Topic = r.Topic,
                QuestionTitle = r.QuestionTitle,
                Answer = r.Answer,
                Time = r.Time,
                Correct = r.Correct,
                Solution = r.Solution,
                Imagedata=r.Imagedata
            }));
        isInitialized = true;
    }
    maxnumber = (from e in res select e.No).Max();
    minumber = (from e in res select e.No).Min();
    range = maxnumber + 1;
    Questions = Questions.OrderByDescending(s => s.SNo).ToList();
    Random rand = new Random();
    number = rand.Next(minumber, range);
    var result = Questions.FirstOrDefault(c => c.SNo == number);
    solution = result.Solution;
    solutionh = "Solution";
    Topic = result.Topic;
    Topich = "Topic";
    time = (result.Time)/60;
    timeh = "Time in minutes";
    QuestionTitle = result.QuestionTitle;
    QuestionTitleh = "QuestionTitle";
    Answer = result.Answer;
    Answerh = "Answer";
    ImageData = result.Imagedata;
}
}
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,420 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,977 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 57,891 Reputation points
    2024-05-11T16:40:39.82+00:00

    Images are displayed in Blazor by having a url that returns an image (show display in browser if url entered) and setting the src of an <img> tag to this url.

    you will need an api that returns an image file response. Your code would typically return a file result.


0 additional answers

Sort by: Most helpful