How to edit Get All Details action on application page to display all details ?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-02-22T14:03:00.82+00:00

I work on EF core 7 blazor . I face issue I can't call Details data from another from application page to get all Data for details model .

meaning I need to display details data as list on application page where Header Id = 1 on action GetAllDetails.

so what I do to make that .

I need to call Application/GetAllDetails to get all Details contain ID AND DetailsName where Header Id=1

public class Details

{

public int ID { get; set; }

public string DetailsName { get; set; }

public int HeaderId { get; set; }

}

application model

 public class Applications

    {

        [Key]

        public int ApplicationID { get; set; }

        public string Section { get; set;}

        public string ApplicationName { get; set; }

     }

generic repository

public interface IRepository<TEntity> where TEntity : class

{

    IEnumerable<TEntity> GetAll();

}

public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class

{

    internal AppsRepositoryDBContext _context;

    internal DbSet<TEntity> dbSet;

 

       public BaseRepository(AppsRepositoryDBContext context)

        {

            _context = context;

            this.dbSet = _context.Set<TEntity>();

        }

    

        public IEnumerable<TEntity> GetAll() => _context.Set<TEntity>().ToList();

   }

on service

 public interface IapplicationService : IRepository<Applications>

    {

       

    }

public class ApplicationService : BaseRepository<Applications>, IapplicationService

    {

        private readonly AppsRepositoryDBContext _context;

        public ApplicationService(AppsRepositoryDBContext context) : base(context)

        {

            _context = context;

        }

    }

on controller application

 [Route("api/[controller]")]

    [ApiController]

    public class ApplicationController : Controller

    {

        private readonly IapplicationService _IapplicationService;

        public ApplicationController(IapplicationService iapplicationService)

        {

            _IapplicationService = iapplicationService;

        }

 [HttpGet]

    public IActionResult GetAllDetails()

    {

//How to get all section 

        return Ok();

       

    }
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,665 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,598 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 29,946 Reputation points
    2023-02-22T20:01:26.2766667+00:00

    You've posted the same code several times. The repository pattern you've come up or copied from the internet does has minor issues. Plus, there's no relationship between Applications and Details.

    Below is a basic example using the Hosted Blazor template.

    I used a standard service pattern in ASP.NET Core which in my opinion, is more versatile. I do use the repository pattern but for only CRUD operations on a single table. Usually business logic and the UI are far more complex.

        public interface IDetailsService
        {
            Task<List<Details>> GetDetialsByHeaderId(int Id);
        }
    
        public class DetailsService : IDetailsService
        {
            private readonly ApiSqliteContext _context;
            public DetailsService(ApiSqliteContext context)
            {
                _context = context;
            }
    
            public async Task<List<Details>> GetDetialsByHeaderId(int Id)
            {
                var query = _context.Details.Where(x => x.HeaderId == Id);
                return await query.ToListAsync();
            }
        }
    

    The service is registered along with the DbContext

        public class ApiSqliteContext : DbContext
        {
            public ApiSqliteContext(DbContextOptions<ApiSqliteContext> options) : base(options) { }
    
            public DbSet<Details> Details { get; set; }
    
        }
    

    Program.cs

    using BlazorWasmHosted.Server.Data;
    using BlazorWasmHosted.Server.Services;
    using Microsoft.AspNetCore.ResponseCompression;
    using Microsoft.EntityFrameworkCore;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddControllersWithViews();
    builder.Services.AddRazorPages();
    
    builder.Services.AddDbContext<ApiSqliteContext>(options =>
           options.UseSqlite(builder.Configuration.GetConnectionString("ApiSqliteConnectionString")));
    
    builder.Services.AddScoped<IDetailsService, DetailsService>();
    
    
    var app = builder.Build();
    
    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
    
        await BlazorWasmHosted.Server.Models.SeedData.InitializeAsync(services);
    }
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseWebAssemblyDebugging();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    
    app.UseBlazorFrameworkFiles();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    
    app.MapRazorPages();
    app.MapControllers();
    app.MapFallbackToFile("index.html");
    
    app.Run();
    

    Entity Framework Model

        public class Details
        {
            public int ID { get; set; }
            public string DetailsName { get; set; }
            public int HeaderId { get; set; }
        }
    

    DTO (shared between the Web API and Blazor)

        public class DetailsDto
        {
            public int ID { get; set; }
            public string DetailsName { get; set; }
            public int HeaderId { get; set; }
        }
    

    Controller Action

        [Route("api/[controller]")]
        [ApiController]
        public class ApplicationController : ControllerBase
        {
            private readonly IDetailsService _detailService;
            public ApplicationController(IDetailsService detailService)
            {
                _detailService = detailService;
            }
            [HttpGet("{id}")]
            public async Task<ActionResult<DetailsDto>> Get(int id)
            {
                List<Data.Details> results = await _detailService.GetDetialsByHeaderId(id);
                IEnumerable<DetailsDto> dto = from d in results
                        select new DetailsDto()
                        {
                            ID = d.ID,
                            DetailsName = d.DetailsName,
                            HeaderId = d.HeaderId
                        };
    
                return Ok(dto.ToList());
    
            }
        }
    

    Blazor WASM Client

    @page "/details"
    @using BlazorWasmHosted.Shared
    @inject HttpClient Http
    
    <PageTitle>Details</PageTitle>
    
    <h3>Details</h3>
    
    @if (details == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Header Id</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var detail in details)
                {
                    <tr>
                        <td>@detail.ID</td>
                        <td>@detail.DetailsName</td>
                        <td>@detail.HeaderId</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        private DetailsDto[]? details;
    
        protected override async Task OnInitializedAsync()
        {
            details = await Http.GetFromJsonAsync<DetailsDto[]>("/api/Application/1");
        }
    }
    

    This site has several tutorials that are very good and illustrate basic programming patterns when working with data, Web API, and Blazor.

    Tutorial: Create a web API with ASP.NET Core

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.