<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp net core blazor &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-core-blazor/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>Help you to find best ASP.NET Core Hosting</description>
	<lastBuildDate>Thu, 30 May 2024 03:43:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp net core blazor &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Basic Concepts and Hosting Models Selection ASP.NET Core Blazor</title>
		<link>https://topreviewhostingasp.net/basic-concepts-and-hosting-models-selection-asp-net-core-blazor/</link>
					<comments>https://topreviewhostingasp.net/basic-concepts-and-hosting-models-selection-asp-net-core-blazor/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 30 May 2024 03:43:56 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core blazor]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[webassembly asp net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3843</guid>

					<description><![CDATA[A summary of some fundamental Blazor ideas, including the benefits and drawbacks of WebAssembly and server models. Blazor Microsoft created the Blazor framework to facilitate the development of contemporary web applications. The primary benefit lies in the fact that developers can utilize C# to directly create dynamic and interactive web applications. To achieve high-performance application [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>A summary of some fundamental Blazor ideas, including the benefits and drawbacks of WebAssembly and server models.</p>
<h2 id="blazor">Blazor</h2>
<p>Microsoft created the Blazor framework to facilitate the development of contemporary web applications. The primary benefit lies in the fact that developers can utilize C# to directly create dynamic and interactive web applications. To achieve high-performance application development, Blazor uses WebAssembly, a technology that lets back-end code run in the browser similarly to JavaScript, to execute C# programs on the client side.</p>
<p>The introduction given above ought to be sufficient to pique the curiosity of back-end developers who typically work with C#. After actually learning it, I believe the learning curve is fairly easy to navigate if you have some prior knowledge of the C# language. If developers are unfamiliar with the front-end and would like to try learning the full-end, I strongly suggest that they use the Blazor framework as a foundation.</p>
<h2 id="blazor-webassembly-vs-blazor-server">Blazor WebAssembly vs. Blazor Server</h2>
<p>Blazor offers two choices for hosting models. Learning was challenging at first. Allow me to clarify the distinctions between the two.</p>
<p><img fetchpriority="high" decoding="async" class=" wp-image-3844 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-webassembly.png" alt="" width="402" height="225" srcset="https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-webassembly.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-webassembly-50x28.png 50w" sizes="(max-width: 402px) 100vw, 402px" /></p>
<p>When a user visits the website, the front end uses SignalR, a C# package that implements the WebSocket two-way communication function, to connect to the back end server. The back end provides the majority of the data.</p>
<p>A few advantages are:</p>
<ul>
<li>Compared to WebAssembly mode, the initial loading speed is faster.</li>
<li>In contrast to WebAssembly&#8217;s static website, the API&#8217;s functionality is retained in the Server model.</li>
</ul>
<p>Limitations:</p>
<ul>
<li>The website cannot be accessed if the network is unstable or breaks midway because SignalR is used to transmit information (if the connection is only momentary, the browser will automatically reconnect).</li>
<li>For the website to continue to function, users must be connected. There is a maximum number of connection pools determined by the hardware. This implies that issues could arise if numerous users attempt to connect at once!?</li>
</ul>
<h3 id="blazor-webassembly">Blazor WebAssembly</h3>
<div class="image-container">As can be observed, the client side handles every aspect of the architecture directly. The standalone Blazor WebAssembly application loads upon user connection, and further operations don&#8217;t need communication with the back-end server.</p>
<p>A few advantages are:</p></div>
<div>
<ul>
<li>It is self-sufficient. Consider it as if you were directly downloading an application. The server is unaffected by further use. It is still functional even if disconnected.</li>
<li>After the user accesses the webpage, they can fully utilize the client resources rather than depending on the server resources because there is no interaction with the backend server.</li>
<li>It is simple to set up and is a static webpage.</li>
</ul>
<p>Limitations:</p>
<ul>
<li>The client must enable WebAssembly, which is becoming more and more popular.</li>
<li>The first time you load the web page, it will take a while because the entire code is loaded on the user&#8217;s side.</li>
<li>Similar to the previous example, please take great care when implementing the code because it cannot be protected once it is sent to the client.</li>
</ul>
<h2 id="how-to-choose-hosting-models">How to choose Hosting Models</h2>
<p>When comparing the two models, it can be seen that each has pros and cons of its own, with the drawbacks potentially being resolved in different ways. For instance, you can use loading effects to fix issues where Blazor Server won&#8217;t work if it can&#8217;t connect, and you can adjust the reconnect message that appears when it does. If Blazor WASM isn&#8217;t loading quickly the first time, you can also use loading effects to fix the issue.</p>
<p>In my opinion, Blazor Server is a good option if the project involves a back-end management system, the user base is predictable, and the database needs to be maintained. Blazor WASM is a good option if the project is just a small informational website.</p>
<h3 id="blazor-hybrid">Blazor Hybrid</h3>
<p>Alternatively, you can select the ASP.NET Core Hosted Blazor WASM Hybrid mode to get the best of both worlds. To put it briefly, the back end uses.NET Core to perform API operations, while the front end is WASM. It resolves issues with Blazor Server&#8217;s need for a constant connection, WASM&#8217;s need to preload pages if a website is too big, and security issues with all codes needing to be forwarded to the client.</p>
<p>Several.NET native application architectures, such as.NET MAUI, WPF, and Windows Forms, can be used to create hybrid applications. I decided to construct it using the.NET Core API. This type of Blazor WASM Hosted is very easy to construct. Simply decide to use Visual Studio to build the Blazor WebAssembly project. Select ASP.NET Core Hosted from the framework selection screen and create it.</p>
<p><img decoding="async" class=" wp-image-3845 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2024/05/create-blazor-wasm-hybrid-project.webp" alt="" width="772" height="511" srcset="https://topreviewhostingasp.net/wp-content/uploads/2024/05/create-blazor-wasm-hybrid-project.webp 1264w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/create-blazor-wasm-hybrid-project-300x199.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/create-blazor-wasm-hybrid-project-1024x678.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/create-blazor-wasm-hybrid-project-768x509.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/create-blazor-wasm-hybrid-project-50x33.webp 50w" sizes="(max-width: 772px) 100vw, 772px" /></p>
<p>The following is the project&#8217;s structure:</p>
<p><img decoding="async" class=" wp-image-3846 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-wasm-hybrid-project-structure.webp" alt="" width="353" height="532" srcset="https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-wasm-hybrid-project-structure.webp 427w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-wasm-hybrid-project-structure-199x300.webp 199w, https://topreviewhostingasp.net/wp-content/uploads/2024/05/blazor-wasm-hybrid-project-structure-33x50.webp 33w" sizes="(max-width: 353px) 100vw, 353px" /></p>
<p><code>BlazorApp1.Client</code> is part of WebAssembly and is mainly responsible for front-end screen display.<br />
<code>BlazorApp1.Server</code> is part of the back-end Web API. Its implementation is consistent with ASP.NET Web API, and the controller controls the API.<br />
<code>BlazorApp1.Shared</code> is the object storage location for use by Client and Server.</p>
</div>
<h2 id="conclusion">Conclusion</h2>
<p>A completely new framework with great efficiency and flexibility is called Blazor. It is ideal for developers who have experience with the C# language. They are aware of the difficulties faced by back-end engineers who lack front-end experience. They can quickly create a front-end and back-end application for basic applications after using it for personal use. Blazor is a good place to start if you want to communicate with the front-end or full-end.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/basic-concepts-and-hosting-models-selection-asp-net-core-blazor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Build Web Application Using Blazor</title>
		<link>https://topreviewhostingasp.net/how-to-build-web-application-using-blazor/</link>
					<comments>https://topreviewhostingasp.net/how-to-build-web-application-using-blazor/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Mon, 15 Aug 2022 05:35:45 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core blazor]]></category>
		<category><![CDATA[asp net tips]]></category>
		<category><![CDATA[asp net tutorial]]></category>
		<category><![CDATA[blazor tips]]></category>
		<category><![CDATA[build web app using blazor]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3129</guid>

					<description><![CDATA[This tutorial introduces the Blazor framework by guiding you in building a simple Web application with C#. What Is Blazor? Blazor has been gaining in popularity, especially after the release of .NET Core 3.0, which enriched it with many interesting features. Subsequent versions of .NET consolidated its foundations, and the interest around it is growing so [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This tutorial introduces the Blazor framework by guiding you in building a simple Web application with C#.</p>



<h2 class="wp-block-heading" id="What-Is-Blazor-">What Is Blazor?</h2>



<p>Blazor has been gaining in popularity, especially after the <a href="https://auth0.com/blog/exploring-dotnet-core-3-whats-new/" target="_blank" rel="noreferrer noopener">release of .NET Core 3.0</a>, which enriched it with many interesting features. Subsequent versions of .NET consolidated its foundations, and the interest around it is growing so much that Microsoft is betting a lot on its future. But what is Blazor exactly?</p>



<p><a href="https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor" target="_blank" rel="noreferrer noopener">Blazor</a> is a programming framework to build client-side Web applications with .NET. It allows .NET developers to use their C# and <a href="https://docs.microsoft.com/en-us/aspnet/core/razor-pages" target="_blank" rel="noreferrer noopener">Razor</a> knowledge to build interactive UIs running in the browser. Developing client-side applications with Blazor brings a few benefits to .NET developers:</p>



<ul>
<li>They use C# and Razor instead of JavaScript and HTML.</li>
<li>They can leverage the whole .NET functionalities.</li>
<li>They can share code across the server and client.</li>
<li>They can use the .NET development tools they are used to.</li>
</ul>



<p>In a nutshell, Blazor promises .NET developers to let them build client Web applications with the development platform they are comfortable with.</p>



<h3 class="wp-block-heading" id="The-hosting-models">The hosting models</h3>



<p>Blazor provides you with two ways to run your Web client application: <em>Blazor Server</em> and <em>Blazor WebAssembly</em>. These are called <em>hosting models</em>.</p>



<p>The <em>Blazor Server</em> hosting model runs your application on the server within an ASP.NET Core application. The UI is sent to the browser, but UI updates and event handling are performed on the server side. This is similar to traditional Web applications, but the communication between the client side and the server side happens over a <a href="https://docs.microsoft.com/en-us/aspnet/core/signalr/introduction" target="_blank" rel="noreferrer noopener">SignalR</a> connection. The following picture gives you an idea of the overall architecture of the Blazor Server hosting model:</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="538" class="wp-image-3130 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-1024x538.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-1024x538.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-300x158.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-768x403.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-1536x806.png 1536w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-2048x1075.png 2048w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-diagram-50x26.png 50w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>



<p>The Blazor Server hosting model provides a few benefits, such as a smaller download size of the client app and the compatibility with not recent browsers. However, it has some drawbacks compared to a classic Single Page Application (SPA), like a higher latency due to the roundtrip between the client and the server for most user interactions and the challenging scalability in high traffic scenarios.</p>



<p>The <em>Blazor WebAssembly</em> hosting model, also known as <em>Blazor WASM</em>, lets your application run entirely on the user&#8217;s browser. The full code of the application, including its dependencies and the .NET runtime, is compiled into <a href="https://webassembly.org/" target="_blank" rel="noreferrer noopener">WebAssembly</a>, downloaded by the user&#8217;s browser, and locally executed. The following picture describes the hosting model of Blazor WebAssembly:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="538" class="wp-image-3131 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-1024x538.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-1024x538.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-300x158.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-768x403.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-1536x806.png 1536w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-2048x1075.png 2048w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-webassembly-diagram2-50x26.png 50w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>The benefits provided by the Blazor WebAssembly hosting model are similar to those provided by Single Page Applications. After the download, the application is independent of the server, apart from the needed interactions. Also, you don&#8217;t need an ASP.NET Core Web server to host your application. You can use any Web server, since the result of the WebAssembly compilation is just a set of static files.</p>



<p>On the other side, you should be aware of the drawbacks of this hosting model. The Blazor WebAssembly hosting model requires that <a href="https://caniuse.com/wasm" target="_blank" rel="noreferrer noopener">the browser supports WebAssembly</a>. In addition, the initial download of the application may take some time.</p>



<h3 class="wp-block-heading" id="Blazor-roadmap">Blazor roadmap</h3>



<p>Blazor promises a great opportunity for .NET developers. Microsoft&#8217;s goals on the Blazor project are very ambitious, especially for Blazor WebAssembly. In their vision, not only will Blazor WebAssembly become the main hosting model, but it will also drive a great revolution in the <strong>development of clients</strong>.</p>



<p>The <a href="https://visualstudiomagazine.com/articles/2019/09/26/blazor-future.aspx" target="_blank" rel="noreferrer noopener">Blazor WebAssembly hosting model</a> will include Single Page Applications compiled into WebAssembly, Progressive Web Apps, hybrid mobile applications, Electron-based desktop applications, and native applications.</p>



<h2 class="wp-block-heading" id="Prerequisites">Prerequisites</h2>



<p>Before starting to build your Blazor application, you need to ensure you have installed the right tools on your machine. In particular, you need .NET 6.0 SDK or above. You can check if you have the correct version installed by typing the following command in a terminal window:</p>



<pre class="wp-block-code"><code>dotnet --version
</code></pre>



<p>You should get the value <code>6.0.100</code> or above as a result. If you don&#8217;t, you should <a href="https://dotnet.microsoft.com/download/dotnet/6.0" target="_blank" rel="noreferrer noopener">download the .NET SDK</a> and install it on your machine.</p>



<p>If you are going to use Visual Studio, be aware that you need to use at least Visual Studio 2019 16.8 or Visual Studio for Mac 8.9.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>Note</strong>: If you update Visual Studio to the latest version, you will get the required .NET SDK bundled.</p>
</blockquote>



<h2 class="wp-block-heading" id="Building-a-Blazor-Server-Application">Building a Blazor Server Application</h2>



<p>To get started with Blazor, you will build a simple quiz application that shows a list of questions with multiple answers and assigns you a score based on the correct answers you provide. You will create this application using the Blazor Server hosting model.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<p>So, create a basic Blazor Server project by typing the following command in a terminal window:</p>



<pre class="wp-block-code"><code>dotnet new blazorserver -o QuizManager
</code></pre>



<p>This command uses the <code>blazorserver</code> template to generate the project for your application in the <code>QuizManager</code> folder. This newly created folder has a lot of content but, apart from the root folder, the relevant folders that you are going to touch are:</p>



<ul>
<li>The <code>Data</code> folder: it contains the models and the services implementing the business logic.</li>
<li>The <code>Pages</code> folder: this contains the Razor components that generate the HTML views. In particular, this folder contains the <code>_Host.cshtml</code> Razor page, which acts as the starting point of the Web UI.</li>
<li>The <code>Shared</code> folder: it contains Razor components and other elements shared among pages</li>
</ul>



<h3 class="wp-block-heading" id="Creating-the-model-and-the-service">Creating the model and the service</h3>



<p>As a first step, delete the files inside the <code>Data</code> folder. Next, add a <code>QuizItem.cs</code> file into this folder and paste in the following code:</p>



<pre class="wp-block-code"><code>// Data/QuizItem.cs

namespace QuizManager.Data
{
    public class QuizItem
    {
        public string Question { get; set; }
        public List&lt;string&gt; Choices { get; set; }
        public int AnswerIndex { get; set; }
        public int Score { get; set; }

        public QuizItem()
        {
            Choices = new List&lt;string&gt;();
        }
    }
}</code></pre>



<p>This class implements the model for each item of the quiz. It provides a question, a list of possible answers, the zero-based index of the correct answer, and the score assigned when the user gives the correct answer.</p>



<p>In the same <code>Data</code> folder, add a second file named <code>QuizService.cs</code> with the following content:</p>



<pre class="wp-block-code"><code>// Data/QuizService.cs

namespace QuizManager.Data
{
    public class QuizService
    {
        private static readonly List&lt;QuizItem&gt; Quiz;

        static QuizService()
        {
            Quiz = new List&lt;QuizItem&gt; {
                new QuizItem
                {
                    Question = "Which of the following is the name of a Leonardo da Vinci's masterpiece?",
                    Choices = new List&lt;string&gt; {"Sunflowers", "Mona Lisa", "The Kiss"},
                    AnswerIndex = 1,
                    Score = 3
                },
                new QuizItem
                {
                    Question = "Which of the following novels was written by Miguel de Cervantes?",
                    Choices = new List&lt;string&gt; {"The Ingenious Gentleman Don Quixote of La Mancia", "The Life of Gargantua and of Pantagruel", "One Hundred Years of Solitude"},
                    AnswerIndex = 0,
                    Score = 5
                }
            };
        }

        public Task&lt;List&lt;QuizItem&gt;&gt; GetQuizAsync()
        {
            return Task.FromResult(Quiz);
        }
    }
}</code></pre>



<p>This class defines a quiz as a list of <code>QuizItem</code> instances initialized by the <code>QuizService()</code> constructor. For simplicity, the list is implemented with a static variable, but in a real-world scenario, it should be persisted into a database. The <code>GetQuizAsync()</code> method simply returns the value of the <code>Quiz</code> variable.</p>



<p>Now, move to the root of your project and edit the <code>Program.cs</code> file by applying the changes shown in the following code:</p>



<pre class="wp-block-code"><code>// Program.cs

using Microsoft.AspNetCore.Components;
// ...other using clauses...

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
// ? existing code
//builder.Services.AddSingleton&lt;WeatherForecastService&gt;();
builder.Services.AddSingleton&lt;QuizService&gt;();
// ☝️ new code

var app = builder.Build();

// ...existing code...</code></pre>



<p>With this change, you registered the <code>QuizService</code> service you defined above instead of the service of the sample application coming with the default Blazor project template.</p>



<h3 class="wp-block-heading" id="Creating-Razor-components">Creating Razor components</h3>



<p>Now that you&#8217;ve created the model and the service of the application, it&#8217;s time to implement the UI. Blazor leverages <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor" target="_blank" rel="noreferrer noopener">Razor</a> as a template processor to produce dynamic HTML. In particular, Blazor uses <a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/components" target="_blank" rel="noreferrer noopener">Razor components</a> to build up the application UI. Razor components are self-contained units of markup and code that can be nested and reused even in other projects. They are implemented in file with the <code>.razor</code> extension.</p>



<p>To show the quiz to the user and let them interact with it, you need to implement a specific view as a Razor component. So, move to the <code>Pages</code> folder and remove the <code>Counter.razor</code> and <code>FetchData.razor</code> files. These files belonged to the default sample project. Then, add in the same folder the <code>QuizViewer.razor</code> file with the following content:</p>



<pre class="wp-block-code"><code>// Pages/QuizViewer.razor

 @page "/quizViewer"

 @using QuizManager.Data
 @inject QuizService QuizRepository

 &lt;h1&gt;Take your quiz!&lt;/h1&gt;
 &lt;p&gt;Your current score is @currentScore&lt;/p&gt;

@if (quiz == null)
{
    &lt;p&gt;&lt;em&gt;Loading...&lt;/em&gt;&lt;/p&gt;
}
else
{
    int quizIndex = 0;
    @foreach (var quizItem in quiz)
    {
        &lt;section&gt;
            &lt;h3&gt;@quizItem.Question&lt;/h3&gt;
            &lt;div class="form-check"&gt;
            @{
                int choiceIndex = 0;
                quizScores.Add(0);
            }
            @foreach (var choice in quizItem.Choices)
            {
                int currentQuizIndex = quizIndex;
                &lt;input class="form-check-input" type="radio" name="@quizIndex" value="@choiceIndex" @onchange="@((eventArgs) =&gt; UpdateScore(Convert.ToInt32(eventArgs.Value), currentQuizIndex))"/&gt;@choice&lt;br&gt;

                choiceIndex++;
            }
            &lt;/div&gt;
        &lt;/section&gt;

        quizIndex++;
    }
}

@code {
    List&lt;QuizItem&gt; quiz;
    List&lt;int&gt; quizScores = new List&lt;int&gt;();
    int currentScore = 0;

    protected override async Task OnInitializedAsync()
    {
        quiz = await QuizRepository.GetQuizAsync();
    }

    void UpdateScore(int chosenAnswerIndex, int quizIndex)
    {
        var quizItem = quiz[quizIndex];

        if (chosenAnswerIndex == quizItem.AnswerIndex)
        {
            quizScores[quizIndex] = quizItem.Score;
        } else
        {
            quizScores[quizIndex] = 0;
        }
        currentScore = quizScores.Sum();
    }
}</code></pre>



<p>Take a look at the code of this component. Its first line uses the <code>@page</code> directive to define this component as a page, which is a UI element that is directly reachable through an address (<code>/quizViewer</code> in this case) in the Blazor&#8217;s routing system. Then, you have the <code>@using</code> directive, which provides access to the <code>QuizManager.Data</code> namespace where you defined the <code>QuizItem</code> model and the <code>QuizService</code> service. The <code>@inject</code> directive asks the dependency injection system to get an instance of the <code>QuizService</code> class mapped to the <code>QuizRepository</code> variable.</p>



<p>After these initializations, you will find the markup defining the UI. As you can see, this part is a mix of HTML and C# code whose purpose is to build the list of questions with the respective possible answers represented as radio buttons.</p>



<p>The final block of the component is enclosed in the <code>@code</code> directive. This is where you put the logic of the component. In the case of the <code>QuizViewer</code> component, you have the <code>OnInitializedAsync()</code> and the <code>UpdateScore()</code> methods. The first method is called when the component is initialized, and it basically gets the quiz data by invoking the <code>GetQuizAsync()</code> method of the <code>QuizRepository</code> service instance. The <code>UpdateScore()</code> method is called when the user clicks one of the proposed answers, and it updates the list of the assigned scores according to the answer chosen by the user. In the same method, the value of the current score is computed and assigned to the <code>currentScore</code> variable. The value of this variable is shown above the list of questions, as you can see in the markup.</p>



<p>Now, go to apply the final touch by moving in the <code>Shared</code> folder and replacing the content of the <code>NavMenu.razor</code> file with the following code:</p>



<pre class="wp-block-code"><code>// Shared/NavMenu.razor

&lt;div class="top-row ps-3 navbar navbar-dark"&gt;
    &lt;div class="container-fluid"&gt;
        &lt;a class="navbar-brand" href=""&gt;QuizManager&lt;/a&gt;
        &lt;button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu"&gt;
            &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt;
        &lt;/button&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;div class="@NavMenuCssClass" @onclick="ToggleNavMenu"&gt;
    &lt;nav class="flex-column"&gt;
        &lt;div class="nav-item px-3"&gt;
            &lt;NavLink class="nav-link" href="" Match="NavLinkMatch.All"&gt;
                &lt;span class="oi oi-home" aria-hidden="true"&gt;&lt;/span&gt; Home
            &lt;/NavLink&gt;
        &lt;/div&gt;
        &lt;div class="nav-item px-3"&gt;
            &lt;NavLink class="nav-link" href="quizViewer"&gt;
                &lt;span class="oi oi-list-rich" aria-hidden="true"&gt;&lt;/span&gt; Quiz
            &lt;/NavLink&gt;
        &lt;/div&gt;
    &lt;/nav&gt;
&lt;/div&gt;

@code {
    private bool collapseNavMenu = true;

    private string? NavMenuCssClass =&gt; collapseNavMenu ? "collapse" : null;

    private void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }
}</code></pre>



<p>The <code>NavMenu.razor</code> file contains the definition of the navigation bar component of the application. The code you put its this file defines a navigation menu of two items: one pointing to the home page and the other to the <code>QuizViewer</code> component.</p>



<p>You&#8217;re not going to change the <em>App</em> component implemented by the <code>App.razor</code> file in the project root folder yet, but it&#8217;s still worth taking a look at anyway.</p>



<pre class="wp-block-code"><code>// App.razor

&lt;Router AppAssembly="@typeof(App).Assembly"&gt;
    &lt;Found Context="routeData"&gt;
        &lt;RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /&gt;
        &lt;FocusOnNavigate RouteData="@routeData" Selector="h1" /&gt;
    &lt;/Found&gt;
    &lt;NotFound&gt;
        &lt;PageTitle&gt;Not found&lt;/PageTitle&gt;
        &lt;LayoutView Layout="@typeof(MainLayout)"&gt;
            &lt;p role="alert"&gt;Sorry, there's nothing at this address.&lt;/p&gt;
        &lt;/LayoutView&gt;
    &lt;/NotFound&gt;
&lt;/Router&gt;</code></pre>



<p>This component attaches the Blazor routing system to your application by using the built-in <em>Router</em> component. It enables navigation among the pages of your application, distinguishing when the page is found from when it does not exist. For more information about the Blazor routing system, check the <a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/routing" target="_blank" rel="noreferrer noopener">official documentation</a>.</p>



<h3 class="wp-block-heading" id="Running-your-Blazor-Server-application">Running your Blazor Server application</h3>



<p>Now you have your quiz application, so launch it by typing the following command in a terminal window:</p>



<pre class="wp-block-code"><code>dotnet run</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>If this is the very first time you run an ASP.NET Core application, you should trust the HTTPS development certificate included in the .NET Core SDK. This task depends on your operating system. Please, take a look at the <a href="https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.0&amp;tabs=visual-studio#trust" target="_blank" rel="noreferrer noopener">official documentation</a> to apply the proper procedure.</strong></p>
<p><strong>You may also be requested to allow the application to access the developer certificate key.</strong></p>
</blockquote>



<p>After a few seconds, you should get your application up and running. Take a look at your terminal window to get the address your application is listening to. In my case, I got the address <a href="https://localhost:7290/" target="_blank" rel="noreferrer noopener"><code>https://localhost:7290</code></a>, and I will refer to it throughout the article.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>Starting with .NET 6.0, any ASP.NET project created through a template is assigned a random port between 5000 and 5300 for HTTP and between 7000 and 7300 for HTTPS. See <a href="https://docs.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-6.0?view=aspnetcore-6.0#tgp" target="_blank" rel="noreferrer noopener">this document</a> for more information.</strong></p>
</blockquote>



<p>So, if you open your browser at that address, you should get access to the home page, as shown by the following picture:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="916" height="653" class="wp-image-3132 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-home-page.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-home-page.png 916w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-home-page-300x214.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-home-page-768x547.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-home-page-50x36.png 50w" sizes="(max-width: 916px) 100vw, 916px" /></figure>



<p>Selecting the <em>Quiz</em> item in the navigation menu, you should get the interactive quiz you built so far. It should look like the following picture</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="935" height="699" class="wp-image-3133 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-quiz.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-quiz.png 935w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-quiz-300x224.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-quiz-768x574.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-quiz-50x37.png 50w" sizes="(max-width: 935px) 100vw, 935px" /></figure>



<p>If you open the developer tools of your browser, click on the <em>Network</em> tab, and refresh, you will discover that the communication between the client side and the server side of your application doesn&#8217;t use HTTP, but it is a bi-directional binary communication managed by SignalR. The following picture shows the WebSocket channel in Chrome developer tools:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="668" class="wp-image-3134 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-signalr-communication-1024x668.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-signalr-communication-1024x668.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-signalr-communication-300x196.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-signalr-communication-768x501.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-signalr-communication-50x33.png 50w, https://topreviewhostingasp.net/wp-content/uploads/2022/08/blazor-server-signalr-communication.png 1269w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Above article is only short introduction about Blazor. But, we promise that we will back with interesting tutorial again in the future. Thank you for your time reading this article</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-build-web-application-using-blazor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
