Како створити апликацију на једној страници помоћу Разор страница са Блазором

У овом чланку ћемо створити апликацију за једну страницу (СПА) помоћу Разор страница у Блазору, уз помоћ првог приступа базе података Ентити Фрамеворк Цоре.

Увод

Апликације са једном страницом (СПА) су веб апликације које учитавају једну ХТМЛ страницу и динамички је ажурирају док корисник комуницира са апликацијом. Направићемо узорак система за управљање записима запослених и извршаваћемо ЦРУД операције на њему.

Користићемо Висуал Студио 2017 и СКЛ Сервер 2014.

Погледајте коначну пријаву.

Предуслови

  • инсталирајте .НЕТ Цоре 2.1 Превиев 2 СДК одавде
  • инсталирајте Висуал Студио 2017 в15.7 или новију верзију одавде
  • инсталирајте АСП.НЕТ Цоре Блазор Лангуаге Сервицес додатак одавде
  • СКЛ Сервер 2008 или новији

Блазор фрамеворк не подржавају верзије испод Висуал Студио 2017 в15.7.

Изворни код

Набавите изворни код од ГитХуб-а.

Креирање табеле

Користићемо ДБ табелу за чување свих евиденција запослених.

Отворите СКЛ Сервер и користите следећу скрипту за креирање Employeeтабеле.

CREATE TABLE Employee ( EmployeeID int IDENTITY(1,1) PRIMARY KEY, Name varchar(20) NOT NULL , City varchar(20) NOT NULL , Department varchar(20) NOT NULL , Gender varchar(6) NOT NULL )

Креирајте веб апликацију Блазор

Отворите Висуал Студио и изаберите „Филе“> „Нев“> „Пројецт“.

Након одабира пројекта, отвориће се дијалог „Нови пројекат“. У левом окну изаберите „.НЕТ Цоре“ у менију Висуал Ц #. Затим одаберите „АСП.НЕТ Цоре Веб Апплицатион“ из доступних типова пројеката. Ставите назив пројекта као „БлазорСПА“и притисните „ОК“.

Након што кликнете на „ОК“, отвориће се нови дијалог у којем ће се тражити да одаберете предложак пројекта. Можете да видите два падајућа менија у горњем левом углу прозора шаблона. Изаберите „.НЕТ Цоре“ и „АСП.НЕТ Цоре 2.0“ из ових падајућих менија. Затим одаберите образац „Блазор (хостирано на АСП.НЕТ Цоре)“ и притисните „ОК“.

Сада ће бити направљено наше решење Блазор. Можете да уочите структуру директоријума у ​​програму Солутион Екплорер, као што је приказано на доњој слици.

Можете приметити да у овом решењу имамо три пројектне датотеке.

  1. БлазорСПА.Цлиент - има код клијента и садржи странице које ће се приказати у прегледачу.
  2. БлазорСПА.Сервер - има кодове на страни сервера као што су операције повезане са ДБ-ом и веб АПИ.
  3. БлазорСПА.Схаред - садржи дељени код којем могу да приступе и клијент и сервер. Садржи наше класе модела.

Скелирање модела на апликацију

За стварање наших модела користимо први приступ основне базе података Ентити Фрамеворк. Нашу класу модела креираћемо у пројекту „БлазорСПА.Схаред“ тако да буде доступна и клијентском и серверском пројекту.

Идите на „Алати“> „НуГет управитељ пакета“> „Конзола управитеља пакета“. Изаберите „БлазорСПА.Схаред“ са падајућег менија „Дефаулт пројецт“. Погледајте доњу слику:

Прво ћемо инсталирати пакет за добављача базе података којег циљамо, а то је СКЛ Сервер у овом случају. Покрените следећу команду:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Будући да користимо Ентити Фрамеворк Тоолс за стварање модела од постојеће базе података, инсталираћемо и пакет алата. Покрените следећу команду:

Install-Package Microsoft.EntityFrameworkCore.Tools

Након што инсталирате оба пакета, скелираћемо наш модел из табела базе података помоћу следеће наредбе:

Scaffold-DbContext "Your connection string here" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Employee

Не заборавите да ставите сопствени низ везе (унутра “”). Након што се ова команда успешно изврши, можете приметити да је креирана фасцикла „Модели“. Садржи две датотеке класе, „миТестДБЦонтект.цс“и „Емплоиее.цс“. Стога смо успешно скелирали наше моделе користећи први приступ Ентити Фрамеворк језгре базе података.

Тренутно ће фасцикла Моделс имати следећу структуру:

Креирање слоја приступа подацима за апликацију

Кликните десним тастером миша на пројекат „БлазорСПА.Сервер“, а затим одаберите „Адд“> „Нев Фолдер“ и именујте фасциклу као „ДатаАццесс“. Додаћемо нашу класу да би обрађивао операције повезане са базом података само у овој фасцикли.

Кликните десним тастером миша на директоријум „ДатаАццесс“ и одаберите „Адд“> „Цласс“. Назовите предавање „ЕмплоиееДатаАццессЛаиер.цс“.

Отворите „ЕмплоиееДатаАццессЛаиер.цс“and put the following code into it:

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 class EmployeeDataAccessLayer { myTestDBContext db = new myTestDBContext(); //To Get all employees details public IEnumerable 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; } } }}

Here we have defined methods to handle database operations. GetAllEmployees will fetch all the employee data from the Employee Table. Similarly, AddEmployee will create a new employee record, and UpdateEmployee will update the record of an existing employee. GetEmployeeData will fetch the record of the employee corresponding to the employee ID passed to it, and DeleteEmployee will delete the employee record corresponding to the employee ID passed to it.

Adding the web API controller to the application

Right click on the “BlazorSPA.Server/Controllers” folder and select “Add” > “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”.

This will create our API EmployeeControllerclass.

We will call the methods of theEmployeeDataAccessLayerclass to fetch data and pass on the data to the client side.

Open “EmployeeController.cs”file and put the following code into it:

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 class EmployeeController : Controller { EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer(); [HttpGet] [Route("api/Employee/Index")] public IEnumerable Index() { return objemployee.GetAllEmployees(); } [HttpPost] [Route("api/Employee/Create")] public void Create([FromBody] Employee employee) { if (ModelState.IsValid) objemployee.AddEmployee(employee); } [HttpGet] [Route("api/Employee/Details/{id}")] public Employee Details(int id) { return objemployee.GetEmployeeData(id); } [HttpPut] [Route("api/Employee/Edit")] public void Edit([FromBody]Employee employee) { if (ModelState.IsValid) objemployee.UpdateEmployee(employee); } [HttpDelete] [Route("api/Employee/Delete/{id}")] public void Delete(int id) { objemployee.DeleteEmployee(id); } }}

At this point of time, our “BlazorSPA.Server” project has the following structure.

We are done with our backend logic. Therefore, we will now proceed to code our client side.

Adding the Razor page to the application

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.

Right click on the “BlazorSPA.Client/Pages” folder and then select “Add” > “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”.

This will add an “EmployeeData.cshtml” page to our “BlazorSPA.Client/Pages” folder. This Razor page will have two files, “EmployeeData.cshtml”andEmployeeData.cshtml.cs”.

Now we will add code to these pages.

EmployeeData.cshtml.cs

Open “EmployeeData.cshtml.cs”and put the following code into it:

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 class EmployeeDataModel : BlazorComponent { [Inject] protected HttpClient Http { get; set; } [Inject] protected IUriHelper UriHelper { get; set; } [Parameter] protected string paramEmpID { get; set; } = "0"; [Parameter] protected string action { get; set; } protected List empList = new List(); protected Employee emp = new Employee(); protected string title { get; set; } protected override async Task OnParametersSetAsync() { if (action == "fetch") { await FetchEmployee(); this.StateHasChanged(); } else if (action == "create") { title = "Add Employee"; emp = new Employee(); } else if (paramEmpID != "0") { if (action == "edit") { title = "Edit Employee"; } else if (action == "delete") { title = "Delete Employee"; } emp = await Http.GetJsonAsync("/api/Employee/Details/" + Convert.ToInt32(paramEmpID)); } } protected async Task FetchEmployee() { title = "Employee Data"; empList = await Http.GetJsonAsync
    
     ("api/Employee/Index"); } protected async Task CreateEmployee() { if (emp.EmployeeId != 0) { await Http.SendJsonAsync(HttpMethod.Put, "api/Employee/Edit", emp); } else { await Http.SendJsonAsync(HttpMethod.Post, "/api/Employee/Create", emp); } UriHelper.NavigateTo("/employee/fetch"); } protected async Task DeleteEmployee() { await Http.DeleteAsync("api/Employee/Delete/" + Convert.ToInt32(paramEmpID)); UriHelper.NavigateTo("/employee/fetch"); } protected void Cancel() { title = "Employee Data"; UriHelper.NavigateTo("/employee/fetch"); } }}
    

Let us understand this code. We have defined a class EmployeeDataModelthat will hold all our methods that we will use in the “EmployeeData.cshtml”page.

We are injecting the HttpClient service to enable web API call and the IUriHelper service to enable URL redirection. After this, we have defined our parameter attributes — paramEmpID and action. These parameters are used in “EmployeeData.cshtml” to define the routes for our page. We have also declared a property title to display the heading to specify the current action that is being performed on the page.

The OnParametersSetAsync method is invoked every time the URL parameters are set for the page. We will check the value of parameter action to identify the current operation on the page.

If the action is set to fetch, then we will invoke the FetchEmployee method to fetch the updated list of employees from the database and refresh the UI using the StateHasChanged method.

We will check if the action attribute of parameter is set to create, then we will set the title of the page to “Add Employee” and create a new object of type Employee. If the paramEmpID is not “0”, then it is either an edit action or a delete 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 paramEmpID property.

The method FetchEmployee will set the title to “Employee Data” and fetch all the employee data by invoking our web API method.

The CreateEmployee method will check if it is invoked to add a new employee record, or to edit an existing employee record. If the EmployeeId property is set, then it is an edit request and we will send a PUT request to the web API. If EmployeeId is not set, then it is a create request and we will send a POST request to web API. We will set the title 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 paramEmpIDproperty.

The DeleteEmployee method will delete the employee record for the employee ID as set in the paramEmpID property. After deletion, the user is redirected to the “/employee/fetch” page.

In the Cancel method, we will set the title property to “Employee Data” and redirect the user to “/employee/fetch” page.

EmployeeData.cshtml

Open the “EmployeeData.cshtml” page and put the following code into it:

@page "/employee/{action}/{paramEmpID}"@page "/employee/{action}"@inherits EmployeeDataModel

@title

@if (action == "fetch"){

Create New

}@if (action == "create" || action == "edit"){
Name Department
Gender -- Select Gender -- Male Female City
await CreateEmployee())" value="Save" />
}else if (action == "delete"){
Name @emp.Name
Gender @emp.Gender
Department @emp.Department
City @emp.City
await DeleteEmployee())" value="Delete" /> }@if (empList == null){

Loading...

}else{ @foreach (var emp in empList)
ID Name Gender Department City
@emp.EmployeeId @emp.Name @emp.Gender @emp.Department @emp.City Edit
}

At the top, we have defined the routes for our page. There are two routes defined:

  1. /employee/{action}/{paramEmpID} : This will accept the action name along with employee ID. This route is invoked when we perform an Edit or Deleteoperation. When we call an edit or delete action on a particular employee’s data, the employee ID is also passed as the URL parameter.
  2. /employee/{action} : 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.

We are also inheriting theEmployeeDataModel class, which is defined in the “EmployeeData.cshtml.cs” file. This will allow us to use the methods defined in the EmployeeDataModel class.

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.

We will show the “Create New” link only if the action is fetch. If the action is create or edit 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 CreateEmployee method whereas clicking on “Cancel” will invoke the Cancel method.

If the action is delete then a table will be displayed with the data of the employee on which the delete action is invoked. We are also displaying two buttons — “Delete” and “Cancel”. Clicking on the “Delete” button will invoke the DeleteEmployee method, and clicking on “Cancel” will invoke the Cancel method.

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.

Adding the link to the Navigation menu

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:

 BlazorSPA 
    
  • Home
  • Employee data
@functions { bool collapseNavMenu = true; void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; }}

Hence, we have successfully created an SPA using Blazor, with the help of the Entity Framework Core database first approach.

Execution demo

Launch the application.

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.

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.

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:

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.

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.

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:

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.

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.

Deploying the application

To learn how to deploy a Blazor application using IIS, refer to Deploying A Blazor Application On IIS.

Conclusion

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.

Please get the source code from GitHub and play around to get a better understanding.

Get my book Blazor Quick Start Guide to learn more about Blazor.

You can also read this article at C# Corner

You can check my other articles on Blazor here.

See Also

  • ASP.NET Core — Getting Started With Blazor
  • ASP.NET Core — CRUD Using Blazor And Entity Framework Core
  • Cascading DropDownList In Blazor Using EF Core
  • Razor Page Web Application With ASP.NET Core Using ADO.NET
  • АСП.НЕТ Цоре - ЦРУД који користи Ангулар 5 и Ентити Фрамеворк Цоре
  • АСП.НЕТ Цоре - ЦРУД са Реацт.јс-ом и Ентити Фрамеворк Цоре-ом

Првобитно објављено на //анкитсхармаблогс.цом/