<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ entity framework - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ entity framework - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 21 Jul 2026 22:37:44 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/entity-framework/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to create a single page application using Razor pages with Blazor ]]>
                </title>
                <description>
                    <![CDATA[ By Ankit Sharma In this article, we are going to create a Single Page Application (SPA) using Razor pages in Blazor, with the help of the Entity Framework Core database first approach. Introduction Single Page Application (SPAs) are web applications ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-a-single-page-application-using-razor-pages-with-blazor-9d010fd6be45/</link>
                <guid isPermaLink="false">66d45da4787a2a3b05af4382</guid>
                
                    <category>
                        <![CDATA[ entity framework ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[  Single Page Applications  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 11 Jun 2018 16:21:44 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*vVXicFhmOOyYASuzkM570w.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ankit Sharma</p>
<p>In this article, we are going to create a Single Page Application (SPA) using Razor pages in Blazor, with the help of the Entity Framework Core database first approach.</p>
<h3 id="heading-introduction">Introduction</h3>
<p>Single Page Application (SPAs) are web applications that load a single HTML page, and dynamically update that page as the user interacts with the app. We will be creating a sample Employee Record Management System and perform CRUD operations on it.</p>
<p>We will be using Visual Studio 2017 and SQL Server 2014.</p>
<p>Take a look at the final application.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/pA8DDQa-ek6BJEKFbMN8ukjS2nv8fFxMJ9In" alt="Image" width="650" height="387" loading="lazy"></p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>install .NET Core 2.1 Preview 2 SDK from <a target="_blank" href="https://www.microsoft.com/net/download/dotnet-core/sdk-2.1.300-preview2">here</a></li>
<li>install Visual Studio 2017 v15.7 or above from <a target="_blank" href="https://www.visualstudio.com/downloads/">here</a></li>
<li>install ASP.NET Core Blazor Language Services extension from <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=aspnet.blazor">here</a></li>
<li>SQL Server 2008 or above</li>
</ul>
<p>The Blazor framework is not supported by versions below Visual Studio 2017 v15.7.</p>
<h3 id="heading-source-code">Source code</h3>
<p>Get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/SPA-With-Blazor">GitHub</a>.</p>
<h3 id="heading-creating-the-table">Creating the table</h3>
<p>We will be using a DB table to store all the records of employees.</p>
<p>Open SQL Server and use the following script to create the<code>Employee</code> table.</p>
<pre><code>CREATE TABLE Employee (  EmployeeID int IDENTITY(<span class="hljs-number">1</span>,<span class="hljs-number">1</span>) PRIMARY KEY,  Name varchar(<span class="hljs-number">20</span>) NOT NULL ,  City varchar(<span class="hljs-number">20</span>) NOT NULL ,  Department varchar(<span class="hljs-number">20</span>) NOT NULL ,  Gender varchar(<span class="hljs-number">6</span>) NOT NULL   )
</code></pre><h3 id="heading-create-the-blazor-web-application">Create the Blazor web application</h3>
<p>Open Visual Studio and select “File” &gt; “New” &gt; “Project”.</p>
<p>After selecting the project, a “New Project” dialog will open. In the left panel, select “.NET Core” inside the Visual C# menu. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as “BlazorSPA” and press “OK”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Mzs4TvnFTePBJQ5wDxkyXwI7VFBjDHUAVZ4e" alt="Image" width="650" height="371" loading="lazy"></p>
<p>After clicking on “OK”, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select the “Blazor (ASP.NET Core hosted)” template and press “OK”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GyYuYmaGwKBRknv04cVsMhZzS65vVbH7qRm3" alt="Image" width="650" height="457" loading="lazy"></p>
<p>Now our Blazor solution will be created. You can observe the folder structure in Solution Explorer as shown in the below image.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/n69NyMxPfNGl7qLqWWrx8YmQOiQeXJy6qUyN" alt="Image" width="268" height="544" loading="lazy"></p>
<p>You can observe that we have three project files created inside this solution.</p>
<ol>
<li>BlazorSPA.Client — has the client side code and contains the pages that will be rendered on the browser.</li>
<li>BlazorSPA.Server — has the server side codes such as DB-related operations and the web API.</li>
<li>BlazorSPA.Shared — contains the shared code that can be accessed by both client and server. It contains our model classes.</li>
</ol>
<h3 id="heading-scaffolding-the-model-to-the-application">Scaffolding the model to the application</h3>
<p>We are using the Entity Framework core database first approach to create our models. We will create our model class in the “BlazorSPA.Shared” project so that it can be accessible to both client and server project.</p>
<p>Navigate to “Tools” &gt; “NuGet Package Manager” &gt; “Package Manager Console”. Select “BlazorSPA.Shared” from the “Default project” dropdown. Refer to the image below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SjjP3ntvRWEycZ-3dX20CSBzezpMxs645EGF" alt="Image" width="650" height="71" loading="lazy"></p>
<p>First, we will install the package for the database provider that we are targeting, which is SQL Server in this case. Run the following command:</p>
<pre><code>Install-Package Microsoft.EntityFrameworkCore.SqlServer
</code></pre><p>Since we are using Entity Framework Tools to create a model from the existing database, we will install the tools package as well. Run the following command:</p>
<pre><code>Install-Package Microsoft.EntityFrameworkCore.Tools
</code></pre><p>After you have installed both the packages, we will scaffold our model from the database tables using the following command:</p>
<pre><code>Scaffold-DbContext <span class="hljs-string">"Your connection string here"</span> Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Employee
</code></pre><p><strong>Do not forget</strong> to put your own connection string (inside <code>“”</code>). After this command is executed successfully, you can observe a “Models” folder has been created. It contains two class files, “myTestDBContext.cs” and “Employee.cs”. Hence, we have successfully scaffolded our models using the Entity Framework core database first approach.</p>
<p>At this point in time, the Models folder will have the following structure:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/gY0lV5KolvXUTFdFkN-gnXvzb0aObcOmAXZz" alt="Image" width="308" height="281" loading="lazy"></p>
<h3 id="heading-creating-the-data-access-layer-for-the-application">Creating the data access layer for the application</h3>
<p>Right-click on the “BlazorSPA.Server” project and then select “Add” &gt; “New Folder” and name the folder as “DataAccess”. We will be adding our class to handle database-related operations inside this folder only.</p>
<p>Right click on the “DataAccess” folder and select “Add” &gt; “Class”. Name your class “EmployeeDataAccessLayer.cs”.</p>
<p>Open “EmployeeDataAccessLayer.cs” and put the following code into it:</p>
<pre><code>using BlazorSPA.Shared.Models;using Microsoft.EntityFrameworkCore;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace BlazorSPA.Server.DataAccess{    public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeDataAccessLayer</span>    </span>{        myTestDBContext db = <span class="hljs-keyword">new</span> myTestDBContext();        <span class="hljs-comment">//To Get all employees details           public IEnumerable&lt;Employee&gt; GetAllEmployees()        {            try            {                return db.Employee.ToList();            }            catch            {                throw;            }        }        //To Add new employee record             public void AddEmployee(Employee employee)        {            try            {                db.Employee.Add(employee);                db.SaveChanges();            }            catch            {                throw;            }        }        //To Update the records of a particluar employee            public void UpdateEmployee(Employee employee)        {            try            {                db.Entry(employee).State = EntityState.Modified;                db.SaveChanges();            }            catch            {                throw;            }        }        //Get the details of a particular employee            public Employee GetEmployeeData(int id)        {            try            {                Employee employee = db.Employee.Find(id);                return employee;            }            catch            {                throw;            }        }        //To Delete the record of a particular employee            public void DeleteEmployee(int id)        {            try            {                Employee emp = db.Employee.Find(id);                db.Employee.Remove(emp);                db.SaveChanges();            }            catch            {                throw;            }        }    }}</span>
</code></pre><p>Here we have defined methods to handle database operations. <code>GetAllEmployees</code> will fetch all the employee data from the Employee Table. Similarly, <code>AddEmployee</code> will create a new employee record, and <code>UpdateEmployee</code> will update the record of an existing employee. <code>GetEmployeeData</code> will fetch the record of the employee corresponding to the employee ID passed to it, and <code>DeleteEmployee</code> will delete the employee record corresponding to the employee ID passed to it.</p>
<h3 id="heading-adding-the-web-api-controller-to-the-application">Adding the web API controller to the application</h3>
<p>Right click on the “BlazorSPA.Server/Controllers” folder and select “Add” &gt; “New Item”. An “Add New Item” dialog box will open. Select “ASP.NET” from the left panel, then select “API Controller Class” from the templates panel, and put the name as “EmployeeController.cs”. Click “Add”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/OZjyShEwULZNifr-ZNzRWY0bjYkAaQKHMNeI" alt="Image" width="650" height="370" loading="lazy"></p>
<p>This will create our API <code>EmployeeController</code> class.</p>
<p>We will call the methods of the<code>EmployeeDataAccessLayer</code> class to fetch data and pass on the data to the client side.</p>
<p>Open “EmployeeController.cs” file and put the following code into it:</p>
<pre><code>using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using BlazorSPA.Server.DataAccess;using BlazorSPA.Shared.Models;using Microsoft.AspNetCore.Mvc;namespace BlazorSPA.Server.Controllers{    public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeController</span> : <span class="hljs-title">Controller</span>    </span>{        EmployeeDataAccessLayer objemployee = <span class="hljs-keyword">new</span> EmployeeDataAccessLayer();        [HttpGet]        [Route(<span class="hljs-string">"api/Employee/Index"</span>)]        public IEnumerable&lt;Employee&gt; Index()        {            <span class="hljs-keyword">return</span> objemployee.GetAllEmployees();        }        [HttpPost]        [Route(<span class="hljs-string">"api/Employee/Create"</span>)]        public <span class="hljs-keyword">void</span> Create([FromBody] Employee employee)        {            <span class="hljs-keyword">if</span> (ModelState.IsValid)                objemployee.AddEmployee(employee);        }        [HttpGet]        [Route(<span class="hljs-string">"api/Employee/Details/{id}"</span>)]        public Employee Details(int id)        {            <span class="hljs-keyword">return</span> objemployee.GetEmployeeData(id);        }        [HttpPut]        [Route(<span class="hljs-string">"api/Employee/Edit"</span>)]        public <span class="hljs-keyword">void</span> Edit([FromBody]Employee employee)        {            <span class="hljs-keyword">if</span> (ModelState.IsValid)                objemployee.UpdateEmployee(employee);        }        [HttpDelete]        [Route(<span class="hljs-string">"api/Employee/Delete/{id}"</span>)]        public <span class="hljs-keyword">void</span> Delete(int id)        {            objemployee.DeleteEmployee(id);        }    }}
</code></pre><p>At this point of time, our “BlazorSPA.Server” project has the following structure.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/DnpONEsQobR0N3YDjCyWRteruR0P-8CvxFug" alt="Image" width="369" height="423" loading="lazy"></p>
<p>We are done with our backend logic. Therefore, we will now proceed to code our client side.</p>
<h3 id="heading-adding-the-razor-page-to-the-application">Adding the Razor page to the application</h3>
<p>We will add the Razor page into the “BlazorSPA.Client/Pages” folder. By default, we have “Counter” and “Fetch Data” pages provided in our application. These default pages will not affect our application but, for the sake of this tutorial, we will delete the “fetchdata” and “counter” pages from the “BlazorSPA.Client/Pages” folder.</p>
<p>Right click on the “BlazorSPA.Client/Pages” folder and then select “Add” &gt; “New Item”. An “Add New Item” dialog box will open. Select “ASP.NET Core” from the left panel, then select “Razor Page” from the templates panel and name it “EmployeeData.cshtml”. Click “Add”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/tR2ue0vJJqAb0HROVGJxob8ZJy13WgbFUav7" alt="Image" width="650" height="370" loading="lazy"></p>
<p>This will add an “EmployeeData.cshtml” page to our “BlazorSPA.Client/Pages” folder. This Razor page will have two files, “EmployeeData.cshtml” and _“<em>EmployeeData.cshtml.cs”</em>._</p>
<p>Now we will add code to these pages.</p>
<h3 id="heading-employeedatacshtmlcs">EmployeeData.cshtml.cs</h3>
<p>Open “EmployeeData.cshtml.cs” and put the following code into it:</p>
<pre><code>using System;using System.Collections.Generic;using System.Linq;using System.Net.Http;using System.Threading.Tasks;using BlazorSPA.Shared.Models;using Microsoft.AspNetCore.Blazor;using Microsoft.AspNetCore.Blazor.Components;using Microsoft.AspNetCore.Blazor.Services;namespace BlazorSPA.Client.Pages{    public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeDataModel</span> : <span class="hljs-title">BlazorComponent</span>    </span>{        [Inject]        protected HttpClient Http { get; set; }        [Inject]        protected IUriHelper UriHelper { get; set; }        [Parameter]        protected string paramEmpID { get; set; } = <span class="hljs-string">"0"</span>;        [Parameter]        protected string action { get; set; }        protected List&lt;Employee&gt; empList = <span class="hljs-keyword">new</span> List&lt;Employee&gt;();        protected Employee emp = <span class="hljs-keyword">new</span> Employee();        protected string title { get; set; }        protected override <span class="hljs-keyword">async</span> Task OnParametersSetAsync()        {            <span class="hljs-keyword">if</span> (action == <span class="hljs-string">"fetch"</span>)            {                <span class="hljs-keyword">await</span> FetchEmployee();                <span class="hljs-built_in">this</span>.StateHasChanged();            }            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (action == <span class="hljs-string">"create"</span>)            {                title = <span class="hljs-string">"Add Employee"</span>;                emp = <span class="hljs-keyword">new</span> Employee();            }            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (paramEmpID != <span class="hljs-string">"0"</span>)            {                <span class="hljs-keyword">if</span> (action == <span class="hljs-string">"edit"</span>)                {                    title = <span class="hljs-string">"Edit Employee"</span>;                }                <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (action == <span class="hljs-string">"delete"</span>)                {                    title = <span class="hljs-string">"Delete Employee"</span>;                }                emp = <span class="hljs-keyword">await</span> Http.GetJsonAsync&lt;Employee&gt;(<span class="hljs-string">"/api/Employee/Details/"</span> + Convert.ToInt32(paramEmpID));            }        }        protected <span class="hljs-keyword">async</span> Task FetchEmployee()        {            title = <span class="hljs-string">"Employee Data"</span>;            empList = <span class="hljs-keyword">await</span> Http.GetJsonAsync&lt;List&lt;Employee&gt;&gt;(<span class="hljs-string">"api/Employee/Index"</span>);        }        protected <span class="hljs-keyword">async</span> Task CreateEmployee()        {            <span class="hljs-keyword">if</span> (emp.EmployeeId != <span class="hljs-number">0</span>)            {                <span class="hljs-keyword">await</span> Http.SendJsonAsync(HttpMethod.Put, <span class="hljs-string">"api/Employee/Edit"</span>, emp);            }            <span class="hljs-keyword">else</span>            {                <span class="hljs-keyword">await</span> Http.SendJsonAsync(HttpMethod.Post, <span class="hljs-string">"/api/Employee/Create"</span>, emp);            }            UriHelper.NavigateTo(<span class="hljs-string">"/employee/fetch"</span>);        }        protected <span class="hljs-keyword">async</span> Task DeleteEmployee()        {            <span class="hljs-keyword">await</span> Http.DeleteAsync(<span class="hljs-string">"api/Employee/Delete/"</span> + Convert.ToInt32(paramEmpID));            UriHelper.NavigateTo(<span class="hljs-string">"/employee/fetch"</span>);        }        protected <span class="hljs-keyword">void</span> Cancel()        {            title = <span class="hljs-string">"Employee Data"</span>;            UriHelper.NavigateTo(<span class="hljs-string">"/employee/fetch"</span>);        }    }}
</code></pre><p>Let us understand this code. We have defined a class <code>EmployeeDataModel</code> that will hold all our methods that we will use in the “EmployeeData.cshtml” page.</p>
<p>We are injecting the <code>HttpClient</code> service to enable web API call and the <code>IUriHelper</code> service to enable URL redirection. After this, we have defined our parameter attributes — <code>paramEmpID</code> and <code>action</code>. These parameters are used in “EmployeeData.cshtml” to define the routes for our page. We have also declared a property <code>title</code> to display the heading to specify the current action that is being performed on the page.</p>
<p>The <code>OnParametersSetAsync</code> method is invoked every time the URL parameters are set for the page. We will check the value of parameter <code>action</code> to identify the current operation on the page.</p>
<p>If the action is set to <code>fetch</code>, then we will invoke the <code>FetchEmployee</code> method to fetch the updated list of employees from the database and refresh the UI using the <code>StateHasChanged</code> method.</p>
<p>We will check if the action attribute of parameter is set to <code>create</code>, then we will set the title of the page to “Add Employee” and create a new object of type <code>Employee</code>. If the <code>paramEmpID</code> is not “0”, then it is either an <code>edit</code> action or a <code>delete</code> action. We will set the title property accordingly and then invoke our web API method to fetch the data for the employee ID as set in the <code>paramEmpID</code> property.</p>
<p>The method <code>FetchEmployee</code> will set the title to “Employee Data” and fetch all the employee data by invoking our web API method.</p>
<p>The <code>CreateEmployee</code> method will check if it is invoked to add a new employee record, or to edit an existing employee record. If the <code>EmployeeId</code> property is set, then it is an <code>edit</code> request and we will send a PUT request to the web API. If <code>EmployeeId</code> is not set, then it is a <code>create</code> request and we will send a POST request to web API. We will set the <code>title</code> property according to the corresponding value of action, and then invoke our web API method to fetch the data for the employee ID as set in the <code>paramEmpID</code> property.</p>
<p>The <code>DeleteEmployee</code> method will delete the employee record for the employee ID as set in the <code>paramEmpID</code> property. After deletion, the user is redirected to the “/employee/fetch” page.</p>
<p>In the <code>Cancel</code> method, we will set the title property to “Employee Data” and redirect the user to “/employee/fetch” page<strong>.</strong></p>
<h3 id="heading-employeedatacshtml">EmployeeData.cshtml</h3>
<p>Open the “EmployeeData.cshtml” page and put the following code into it:</p>
<pre><code>@page <span class="hljs-string">"/employee/{action}/{paramEmpID}"</span>@page <span class="hljs-string">"/employee/{action}"</span>@inherits EmployeeDataModel&lt;h1&gt;@title&lt;<span class="hljs-regexp">/h1&gt;@if (action == "fetch"){    &lt;p&gt;        &lt;a href="/</span>employee/create<span class="hljs-string">"&gt;Create New&lt;/a&gt;    &lt;/p&gt;}@if (action == "</span>create<span class="hljs-string">" || action == "</span>edit<span class="hljs-string">"){    &lt;form&gt;        &lt;table class="</span>form-group<span class="hljs-string">"&gt;            &lt;tr&gt;                &lt;td&gt;                    &lt;label for="</span>Name<span class="hljs-string">" class="</span>control-label<span class="hljs-string">"&gt;Name&lt;/label&gt;                &lt;/td&gt;                &lt;td&gt;                    &lt;input type="</span>text<span class="hljs-string">" class="</span>form-control<span class="hljs-string">" bind="</span>@emp.Name<span class="hljs-string">" /&gt;                &lt;/td&gt;                &lt;td width="</span><span class="hljs-number">20</span><span class="hljs-string">"&gt; &lt;/td&gt;                &lt;td&gt;                    &lt;label for="</span>Department<span class="hljs-string">" class="</span>control-label<span class="hljs-string">"&gt;Department&lt;/label&gt;                &lt;/td&gt;                &lt;td&gt;                    &lt;input type="</span>text<span class="hljs-string">" class="</span>form-control<span class="hljs-string">" bind="</span>@emp.Department<span class="hljs-string">" /&gt;                &lt;/td&gt;            &lt;/tr&gt;            &lt;tr&gt;                &lt;td&gt;                    &lt;label for="</span>Gender<span class="hljs-string">" class="</span>control-label<span class="hljs-string">"&gt;Gender&lt;/label&gt;                &lt;/td&gt;                &lt;td&gt;                    &lt;select asp-for="</span>Gender<span class="hljs-string">" class="</span>form-control<span class="hljs-string">" bind="</span>@emp.Gender<span class="hljs-string">"&gt;                        &lt;option value="</span><span class="hljs-string">"&gt;-- Select Gender --&lt;/option&gt;                        &lt;option value="</span>Male<span class="hljs-string">"&gt;Male&lt;/option&gt;                        &lt;option value="</span>Female<span class="hljs-string">"&gt;Female&lt;/option&gt;                    &lt;/select&gt;                &lt;/td&gt;                &lt;td width="</span><span class="hljs-number">20</span><span class="hljs-string">"&gt; &lt;/td&gt;                &lt;td&gt;                    &lt;label for="</span>City<span class="hljs-string">" class="</span>control-label<span class="hljs-string">"&gt;City&lt;/label&gt;                &lt;/td&gt;                &lt;td&gt;                    &lt;input type="</span>text<span class="hljs-string">" class="</span>form-control<span class="hljs-string">" bind="</span>@emp.City<span class="hljs-string">" /&gt;                &lt;/td&gt;            &lt;/tr&gt;            &lt;tr&gt;                &lt;td&gt;&lt;/td&gt;                &lt;td&gt;                    &lt;input type="</span>submit<span class="hljs-string">" class="</span>btn btn-success<span class="hljs-string">" onclick="</span>@(<span class="hljs-keyword">async</span> () =&gt; <span class="hljs-keyword">await</span> CreateEmployee())<span class="hljs-string">" style="</span>width:<span class="hljs-number">220</span>px;<span class="hljs-string">" value="</span>Save<span class="hljs-string">" /&gt;                &lt;/td&gt;                &lt;td&gt;&lt;/td&gt;                &lt;td width="</span><span class="hljs-number">20</span><span class="hljs-string">"&gt; &lt;/td&gt;                &lt;td&gt;                    &lt;input type="</span>submit<span class="hljs-string">" class="</span>btn btn-danger<span class="hljs-string">" onclick="</span>@Cancel<span class="hljs-string">" style="</span>width:<span class="hljs-number">220</span>px;<span class="hljs-string">" value="</span>Cancel<span class="hljs-string">" /&gt;                &lt;/td&gt;            &lt;/tr&gt;        &lt;/table&gt;    &lt;/form&gt;}else if (action == "</span><span class="hljs-keyword">delete</span><span class="hljs-string">"){    &lt;div class="</span>col-md<span class="hljs-number">-4</span><span class="hljs-string">"&gt;        &lt;table class="</span>table<span class="hljs-string">"&gt;            &lt;tr&gt;                &lt;td&gt;Name&lt;/td&gt;                &lt;td&gt;@emp.Name&lt;/td&gt;            &lt;/tr&gt;            &lt;tr&gt;                &lt;td&gt;Gender&lt;/td&gt;                &lt;td&gt;@emp.Gender&lt;/td&gt;            &lt;/tr&gt;            &lt;tr&gt;                &lt;td&gt;Department&lt;/td&gt;                &lt;td&gt;@emp.Department&lt;/td&gt;            &lt;/tr&gt;            &lt;tr&gt;                &lt;td&gt;City&lt;/td&gt;                &lt;td&gt;@emp.City&lt;/td&gt;            &lt;/tr&gt;        &lt;/table&gt;        &lt;div class="</span>form-group<span class="hljs-string">"&gt;            &lt;input type="</span>submit<span class="hljs-string">" class="</span>btn btn-danger<span class="hljs-string">" onclick="</span>@(<span class="hljs-keyword">async</span> () =&gt; <span class="hljs-keyword">await</span> DeleteEmployee())<span class="hljs-string">" value="</span>Delete<span class="hljs-string">" /&gt;            &lt;input type="</span>submit<span class="hljs-string">" value="</span>Cancel<span class="hljs-string">" onclick="</span>@Cancel<span class="hljs-string">" class="</span>btn<span class="hljs-string">" /&gt;        &lt;/div&gt;    &lt;/div&gt;}@if (empList == null){    &lt;p&gt;&lt;em&gt;Loading...&lt;/em&gt;&lt;/p&gt;}else{    &lt;table class='table'&gt;        &lt;thead&gt;            &lt;tr&gt;                &lt;th&gt;ID&lt;/th&gt;                &lt;th&gt;Name&lt;/th&gt;                &lt;th&gt;Gender&lt;/th&gt;                &lt;th&gt;Department&lt;/th&gt;                &lt;th&gt;City&lt;/th&gt;            &lt;/tr&gt;        &lt;/thead&gt;        &lt;tbody&gt;            @foreach (var emp in empList)            {                &lt;tr&gt;                    &lt;td&gt;@emp.EmployeeId&lt;/td&gt;                    &lt;td&gt;@emp.Name&lt;/td&gt;                    &lt;td&gt;@emp.Gender&lt;/td&gt;                    &lt;td&gt;@emp.Department&lt;/td&gt;                    &lt;td&gt;@emp.City&lt;/td&gt;                    &lt;td&gt;                        &lt;a href='/employee/edit/@emp.EmployeeId'&gt;Edit&lt;/a&gt;  |                        &lt;a href='/employee/delete/@emp.EmployeeId'&gt;Delete&lt;/a&gt;                    &lt;/td&gt;                &lt;/tr&gt;            }        &lt;/tbody&gt;    &lt;/table&gt;}</span>
</code></pre><p>At the top, we have defined the routes for our page. There are two routes defined:</p>
<ol>
<li><code>/employee/{action}/{paramEmpID}</code> : This will accept the action name along with employee ID. This route is invoked when we perform an Edit or Delete operation<em>.</em> When we call an <code>edit</code> or <code>delete</code> action on a particular employee’s data, the employee ID is also passed as the URL parameter.</li>
<li><code>/employee/{action}</code> : This will only accept the action name. This route is invoked when we create a new employee’s data, or we fetch the records of all the employees.</li>
</ol>
<p>We are also inheriting the<code>EmployeeDataModel</code> class, which is defined in the “EmployeeData.cshtml.cs” file. This will allow us to use the methods defined in the <code>EmployeeDataModel</code> class.</p>
<p>After this, we are setting the title that will be displayed on our page. The title is dynamic and changes as per the action that is being executed currently on the page.</p>
<p>We will show the “Create New” link only if the action is <code>fetch</code>. If the action is <code>create</code> or <code>edit</code> then the “Create New” link will be hidden and we will display the form to get the user input. Inside the form, we have also defined the two buttons “Save” and “Cancel”. Clicking on “Save” will invoke the <code>CreateEmployee</code> method whereas clicking on “Cancel” will invoke the <code>Cancel</code> method.</p>
<p>If the action is <code>delete</code> then a table will be displayed with the data of the employee on which the <code>delete</code> action is invoked. We are also displaying two buttons — “Delete” and “Cancel”. Clicking on the “Delete” button will invoke the <code>DeleteEmployee</code> method, and clicking on “Cancel” will invoke the <code>Cancel</code> method.</p>
<p>At the end, we have a table to display all the employee data from the database. Each employee record will also have two action links: “Edit” to edit the employee record and “Delete” to delete the employee record. This table is always displayed on the page, and we will update it after performing every action.</p>
<h3 id="heading-adding-the-link-to-the-navigation-menu">Adding the link to the Navigation menu</h3>
<p>The last step is to add the link to our “EmployeeData” page in the navigation menu. Open the “BlazorSPA.Client/Shared/NavMenu.cshtml” page and put the following code into it:</p>
<pre><code>&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"top-row pl-4 navbar navbar-dark"</span>&gt;    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-brand"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>&gt;</span>BlazorSPA<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span>    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-toggler"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">@ToggleNavMenu</span>&gt;</span>        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-toggler-icon"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>&lt;<span class="hljs-regexp">/div&gt;&lt;div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu&gt;    &lt;ul class="nav flex-column"&gt;        &lt;li class="nav-item px-3"&gt;            &lt;NavLink class="nav-link" href="/</span><span class="hljs-string">" Match=NavLinkMatch.All&gt;                &lt;span class="</span>oi oi-home<span class="hljs-string">" aria-hidden="</span><span class="hljs-literal">true</span><span class="hljs-string">"&gt;&lt;/span&gt; Home            &lt;/NavLink&gt;        &lt;/li&gt;        &lt;li class="</span>nav-item px<span class="hljs-number">-3</span><span class="hljs-string">"&gt;            &lt;NavLink class="</span>nav-link<span class="hljs-string">" href="</span>/employee/fetch<span class="hljs-string">"&gt;                &lt;span class="</span>oi oi-list-rich<span class="hljs-string">" aria-hidden="</span><span class="hljs-literal">true</span><span class="hljs-string">"&gt;&lt;/span&gt; Employee data            &lt;/NavLink&gt;        &lt;/li&gt;    &lt;/ul&gt;&lt;/div&gt;@functions {    bool collapseNavMenu = true;    void ToggleNavMenu()    {        collapseNavMenu = !collapseNavMenu;    }}</span>
</code></pre><p>Hence, we have successfully created an SPA using Blazor, with the help of the Entity Framework Core database first approach.</p>
<h3 id="heading-execution-demo">Execution demo</h3>
<p>Launch the application.</p>
<p>A web page will open as shown in the image below. The navigation menu on the left is showing the navigation link for the Employee data page.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/5aytCUZiGENxmbG8UmH3Kkn93L6QlmU3o90I" alt="Image" width="650" height="377" loading="lazy"></p>
<p>Clicking on the “Employee data” link will redirect to the “Employee Data” view. Here you can see all the employee data on the page. Notice the URL has “employee/fetch” appended to it.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/e1LB246vIs1UwwYqU4hb7kgEqktwtXg6QxIW" alt="Image" width="650" height="295" loading="lazy"></p>
<p>We have not added any data, hence it is empty. Click on “CreateNew” to open the “Add Employee” form to add new employee data. Notice the URL has “employee/create” appended to it:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GhLUT-gjoQoOLHv8ldQElEqINjpFE-YoCyd4" alt="Image" width="650" height="346" loading="lazy"></p>
<p>After inserting data in all the fields, click on the “Save” button. The new employee record will be created, and the Employee data table will get refreshed.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VkPKhxGiT5Pg9aEjgZtsSiSqFdaT3fUnosFe" alt="Image" width="650" height="346" loading="lazy"></p>
<p>If we want to edit an existing employee record, then click on the “Edit” action link. It will open Edit view as shown below. Here we can change the employee data. Notice that we have passed the employee ID in the URL parameter.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/a83joAzqvLOvLkrBphgo1X1iNMCJZX4h3hW1" alt="Image" width="650" height="400" loading="lazy"></p>
<p>Here we have changed the City of employee Swati from Mumbai to Kolkatta. Click on “Save” to refresh the employee data table to view the updated changes as highlighted in the image below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/YTVLVrodvmccRgROnCHeUoYjJDc4gCYo9ma0" alt="Image" width="650" height="400" loading="lazy"></p>
<p>Now we will perform a Delete operation on the employee named Dhiraj. Click on the “Delete” action link, which will open the Delete view asking for a confirmation to delete. Notice that we have passed the employee ID in the URL parameter.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/vh9OcLX0TZBjpK4FZZRgNdULvxM45sPSZfBq" alt="Image" width="650" height="484" loading="lazy"></p>
<p>Once we click on the “Delete” button, it will delete the employee record and the employee data table will be refreshed. Here, we can see that the employee with name Dhiraj has been removed from our record.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/6GYVO2fxT7YUq9pkt5taPVC9dCtTQOlnPnMj" alt="Image" width="650" height="318" loading="lazy"></p>
<h3 id="heading-deploying-the-application">Deploying the application</h3>
<p>To learn how to deploy a Blazor application using IIS, refer to <a target="_blank" href="http://ankitsharmablogs.com/deploying-a-blazor-application-on-iis/">Deploying A Blazor Application On IIS</a>.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>We have created a Single Page Application with Razor pages in Blazor using the Entity Framework Core database first approach with the help of Visual Studio 2017 and SQL Server 2014. We have also performed the CRUD operations on our application.</p>
<p>Please get the source code from <a target="_blank" href="https://github.com/AnkitSharma-007/SPA-With-Blazor">GitHub</a> and play around to get a better understanding.</p>
<p>Get my book <a target="_blank" href="https://www.amazon.com/Blazor-Quick-Start-Guide-applications/dp/178934414X/ref=sr_1_1?ie=UTF8&amp;qid=1542438251&amp;sr=8-1&amp;keywords=Blazor-Quick-Start-Guide">Blazor Quick Start Guide</a> to learn more about Blazor.</p>
<p>You can also read this article at <a target="_blank" href="https://www.c-sharpcorner.com/article/creating-a-spa-using-razor-pages-with-blazor/">C# Corner</a></p>
<p>You can check my other articles on Blazor <a target="_blank" href="http://ankitsharmablogs.com/category/blazor/">here</a>.</p>
<h3 id="heading-see-also">See Also</h3>
<ul>
<li><a target="_blank" href="http://ankitsharmablogs.com/asp-net-core-getting-started-with-blazor/">ASP.NET Core — Getting Started With Blazor</a></li>
<li><a target="_blank" href="http://ankitsharmablogs.com/asp-net-core-crud-using-blazor-and-entity-framework-core/">ASP.NET Core — CRUD Using Blazor And Entity Framework Core</a></li>
<li><a target="_blank" href="http://ankitsharmablogs.com/cascading-dropdownlist-in-blazor-using-ef-core/">Cascading DropDownList In Blazor Using EF Core</a></li>
<li><a target="_blank" href="https://www.c-sharpcorner.com/article/razor-page-web-application-with-asp-net-core-using-ado-net/">Razor Page Web Application With ASP.NET Core Using ADO.NET</a></li>
<li><a target="_blank" href="http://ankitsharmablogs.com/asp-net-core-crud-using-angular-5-and-entity-framework-core/">ASP.NET Core — CRUD Using Angular 5 And Entity Framework Core</a></li>
<li><a target="_blank" href="http://ankitsharmablogs.com/asp-net-core-crud-with-react-js-and-entity-framework-core/">ASP.NET Core — CRUD With React.js And Entity Framework Core</a></li>
</ul>
<p>Originally published at <a target="_blank" href="https://ankitsharmablogs.com/">https://ankitsharmablogs.com/</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
