Build Master Detail CRUD in ASP.NET Core 3.1 Blazor

Build-Master-Detail-CRUD-in-ASP.NET-Core-3.1-Blazor image

Master-Detail is a page that manages two related information in which the master present items and the detail page presents details about the item. This article explains how to build simple master-detail in APS.NET Core 3.1 Blazor.
At the end of this article, you should be able to:
  1. Build a master-detail in Blazor. 
  2. Use Blazor components.
  3. Use IJSRuntime to call JavaScript functions from .NET methods.
  4. Call Web APIs in Blazor.
  5. Interact with Database.
  6. Run Blazor Application from ASP.NET Core Application.

Prerequisites
  1. Visual Studio 2019
  2. .NET Core 3.1 SDK Installed
  3. Blazor WebAssembly template installed
Create The Project
  • Create a new project
  • Select Blazor App
  • Name the project MasterDetailCRUD
  • Select Blazor WebAssembly App template then click create
  • Build, and run the default application.
Modify the NavMenu.razor file in the shared folder like so:

 <div class="top-row pl-4 navbar navbar-dark">  
   <a class="navbar-brand" href="">Master Detail CRUD</a>  
   <button class="navbar-toggler" @onclick="ToggleNavMenu">  
     <span class="navbar-toggler-icon"></span>  
   </button>  
 </div>  
 <div class="@NavMenuCssClass" @onclick="ToggleNavMenu">  
   <ul class="nav flex-column">  
     <li class="nav-item px-3">  
        <NavLink class="nav-link" href="" Match="NavLinkMatch.All">  
          <span class="oi oi-home" aria-hidden="true"></span> Home  
        </NavLink>  
      </li>  
    </ul>  
  </div>  
  @code {  
    private bool collapseNavMenu = true;  
    private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;  
    private void ToggleNavMenu()  
    {  
      collapseNavMenu = !collapseNavMenu;  
    }  
  }  

Also, modify the MainLayout.razor like so:

 @inherits LayoutComponentBase  
 <div class="sidebar">  
   <NavMenu />  
 </div>  
 <div class="main">  
   <div class="top-row px-4">  
   </div>  
   <div class="content px-4">  
     @Body  
    </div>  
  </div>  

Add Models
  • Right-click the project solution > Add > New project
  • Select Class Library (.NET Framework) from the templates
  • Name the project MasterDetailCRUD.Models.
Create OrderDetail model like so:

 namespace MasterDetailCRUD.Models  
 {  
   public class OrderDetail  
   {  
     public int OrderDetailId { get; set; }  
     public decimal Price { get; set; }  
     public int Quantity { get; set; }  
     public string Item { get; set; }  
     public int OrderId { get; set; }  
     public decimal TotalPerItem { get => Quantity * Price; }  
    }  
  }  

Add Order and OrderViewModel model like so:

 using System;  
 using System.Collections.Generic;  
 namespace MasterDetailCRUD.Models  
 {  
   public class Order  
   {  
     public int OrderId { get; set; }  
     public string OrderNumber { get; set; }  
     public string CustomerName { get; set; }  
     public string PaymentMethod { get; set; }  
     public DateTime DateCreated { get; set; }  
     public decimal Total { get; set; }  
     public string Status { get; set; }  
     public IEnumerable<OrderDetail> OrderDetails { get; set; }  
     public Order()  
     {  
       OrderDetails = new List<OrderDetail>();  
     }  
    }  
    public class OrderViewModel  
    {  
      public bool ShowDetail { get; set; }  
      public string DetailIcon { get; set; } = "oi-caret-right";  
      public int OrderId { get; set; }  
      public string OrderNumber { get; set; }  
      public string CustomerName { get; set; }  
      public string PaymentMethod { get; set; }  
      public DateTime DateCreated { get; set; }  
      public decimal Total { get; set; }  
      public string Status { get; set; }  
      public IEnumerable<OrderDetail> OrderDetails { get; set; }  
      public OrderViewModel()  
      {  
        OrderDetails = new List<OrderDetail>();  
      }  
    }  
  }  

Setup Database
  • Right-click on the solution > Add >New project
  • Select ASP.NET Core Web Application 
  • Name the project MasterDetailCRUD.Server and click create
  • Select the Empty project template and click create
  • Add reference to the MasterDetail.models project
  • Right-click on the MasterDetailCRUD.Server > Add  > Class
  • Name the dbcontext class  CustomerOderContext.
Modify the CustomerOderContext like so:

 using MasterDetailCRUD.Models;  
 using Microsoft.EntityFrameworkCore;  
 namespace MasterDetailCRUD.Server  
 {  
   public class CustomerOderContext : DbContext  
   {  
     public CustomerOderContext()  
     {  
     }  
      public CustomerOderContext(DbContextOptions options):base(options)  
      {  
      }  
      public DbSet<Order> Orders { get; set; }  
      public DbSet<OrderDetail> OrderDetails { get; set; }  
    }  
  }  

Create Seed Data
Add new class named SeedData to the MasterDetailCRUD.Server Project
Modify the SeedData class like so:

 using MasterDetailCRUD.Models;  
 using System;  
 namespace MasterDetailCRUD.Server  
 {  
   public class SeedData  
   {  
     public static void Initialize(CustomerOderContext db)  
     {  
       var order = new Order()  
        {  
          CustomerName = "Test Customer",  
          PaymentMethod = "Cash",  
          DateCreated = DateTime.Now,  
          Status = "P",  
          Total = 67000.00m,  
          OrderNumber = "456712",  
        };  
        db.Orders.Add(order);  
        db.SaveChanges();  
        var orderdetail = new OrderDetail()  
        {  
          Item = "Iphone X max",  
          Quantity = 2,  
          OrderId = order.OrderId,  
          Price = 32.00m,  
        };  
        db.OrderDetails.Add(orderdetail);  
        db.SaveChanges();  
      }  
    }  
  }  
The seed data will be used to initialize the empty database. This ensure the database have default record.
Modify the Program.cs file to use the seed data when the database is created like so:

 using Microsoft.AspNetCore.Hosting;  
 using Microsoft.Extensions.DependencyInjection;  
 using Microsoft.Extensions.Hosting;  
 namespace MasterDetailCRUD.Server  
 {  
   public class Program  
   {  
     public static void Main(string[] args)  
     {  
        var host = CreateHostBuilder(args).Build();  
        var scopeFactory = host.Services.GetRequiredService<IServiceScopeFactory>();  
        using (var scope = scopeFactory.CreateScope())  
        {  
          var db = scope.ServiceProvider.GetRequiredService<CustomerOderContext>();  
          if (db.Database.EnsureCreated())  
          {  
            SeedData.Initialize(db);  
          }  
        }  
        host.Run();  
      }  
      public static IHostBuilder CreateHostBuilder(string[] args) =>  
        Host.CreateDefaultBuilder(args)  
          .ConfigureWebHostDefaults(webBuilder =>  
          {  
            webBuilder.UseStartup<Startup>();  
          });  
    }  
  }  

Next, configure the services in application startup to use the CustomerOderContext class like so:

using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.Extensions.Hosting;  
namespace MasterDetailCRUD.Server  
{  
  public class Startup  
  {  
     // This method gets called by the runtime. Use this method to add services to the container.  
     // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
     public void ConfigureServices(IServiceCollection services)  
     {  
       services.AddMvc();  
       services.AddDbContext<CustomerOderContext>(option => option.UseSqlite("Data Source=CustomerOrder.db"));  
     }  
     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
     {  
       if (env.IsDevelopment())  
       {  
         app.UseDeveloperExceptionPage();  
       }  
       app.UseStaticFiles();  
       app.UseRouting();  
       app.UseEndpoints(endpoints =>  
       {  
         endpoints.MapControllers();  
       });  
     }  
   }  
  }  

The above uses Sqlite and create CustomerOrder database.

Add OrderController
Right click the MasterDetailCRUD.Server project, add a new class called OrderController.cs.
Modify the class like so.

 using MasterDetailCRUD.Models;  
 using Microsoft.AspNetCore.Mvc;  
 using Microsoft.EntityFrameworkCore;  
 using System;  
 using System.Collections.Generic;  
 using System.Threading.Tasks;  
 namespace MasterDetailCRUD.Server  
 {  
   [Route("Orders")]  
    [ApiController]  
    public class OrderController : Controller  
    {  
      private readonly CustomerOderContext db;  
      public OrderController(CustomerOderContext _db)  
      {  
        db = _db;  
      }  
      [HttpGet]  
      public async Task<List<OrderViewModel>> GetOrders()  
      {  
        var model = new List<OrderViewModel>();  
        try  
        {  
          var data =await db.Orders.Include(j => j.OrderDetails).ToListAsync();  
          foreach (var item in data)  
          {  
            model.Add(new OrderViewModel()  
            {  
              DateCreated = item.DateCreated,  
              CustomerName = item.CustomerName,  
              PaymentMethod = item.PaymentMethod,  
              OrderDetails = item.OrderDetails,  
              OrderNumber = item.OrderNumber,  
              Status = item.Status,  
              OrderId = item.OrderId,  
              Total = item.Total,  
            });  
          }  
        }  
        catch (Exception)  
        {  
        }  
        return model;  
      }  
      [HttpPost]  
      public async Task<ActionResult<int>> PostOrder(Order order)  
      {  
        try  
        {  
          order.Status = "P";  
          order.DateCreated = DateTime.Now;  
          var OrderDetails = order.OrderDetails;  
          order.OrderDetails = null;  
          await db.Orders.AddAsync(order);  
          await db.SaveChangesAsync();  
          var orderdetail = new List<OrderDetail>();  
          foreach (var detail in OrderDetails)  
          {  
            detail.OrderDetailId = 0;  
            detail.OrderId = order.OrderId;  
            orderdetail.Add(detail);  
          }  
          await db.OrderDetails.AddRangeAsync(orderdetail);  
          await db.SaveChangesAsync();  
        }  
        catch (Exception)  
        {  
          return -1;  
        }  
        return order.OrderId;  
      }  
    }  
  }  

The OrderController inherits from Controller class and it is decorated with ApiController attribute. It has two methods, the GetOrders method that retrieves list of customer orders and the PostOrder method which persists new customer order to the CustmerOrder database.

Configure ASP.NET Core project to run the Blazor Application
We want to be able to run MasterDetailCRUD blazor project using the MasterDetailCRUD.Server  ASP.NET Core project.
In the MasterDetailCRUD.Server project, use package manager console to install the following:

 Install-Package Microsoft.AspNetCore.Blazor.Server -Version 3.1.0-preview3.19555.2  

Add project reference of MasterDetailCRUD blazor project to MasterDetailCRUD.Server.
Modify the Startup file like so:

 using Microsoft.AspNetCore.Builder;  
 using Microsoft.AspNetCore.Hosting;  
 using Microsoft.EntityFrameworkCore;  
 using Microsoft.Extensions.DependencyInjection;  
 using Microsoft.Extensions.Hosting;  
 namespace MasterDetailCRUD.Server  
 {  
   public class Startup  
   {  
      // This method gets called by the runtime. Use this method to add services to the container.  
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
      public void ConfigureServices(IServiceCollection services)  
      {  
        services.AddMvc();  
        services.AddDbContext<CustomerOderContext>(option => option.UseSqlite("Data Source=CustomerOrder.db"));  
      }  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
      {  
        if (env.IsDevelopment())  
        {  
          app.UseDeveloperExceptionPage();  
        }  
        app.UseStaticFiles();  
        app.UseRouting();  
        app.UseClientSideBlazorFiles<MasterDetailCRUD.Startup>();  
        app.UseEndpoints(endpoints =>  
        {  
          endpoints.MapControllers();  
          endpoints.MapFallbackToClientSideBlazor<MasterDetailCRUD.Startup>("index.html");  
        });  
      }  
    }  
  }  

Set MasterDetailCRUD.Server as the start project, build and run the project.

Lets take a break so as to keep the article as simple as possible.
The second part concludes this article.

Download Source Code
                                         
                                                                                                                                   Part II >>
Build Master Detail CRUD in ASP.NET Core 3.1 Blazor Build Master Detail CRUD in ASP.NET Core 3.1  Blazor Reviewed by Akintunde Toba on February 26, 2020 Rating: 5

No comments:

Home Ads

Powered by Blogger.