locked
how to display list page in blazor RRS feed

  • Question

  • User-91993069 posted

    I am working with codefirst approach in blazor and mydatabase created successfully using code first approach

    fist I create a project and then select a visual studio 2019 -> blazor app -> blazor server app

    why my employee list page not render in blazor

    I want to display emp table record in blazor but issue is not render

    Emp.cs

    namespace BlazorServerApp.Pages
    {
        public class Emp
        {
            public int empid { get; set; }
            public string empname { get; set; }
            public string empcountry { get; set; }
        }
    }

    EmployeAccessLayer.css

    namespace BlazorServerApp.DataAccess
    {
        public interface IEmployeAccessLayer
        {
            IEnumerable GetAllEmployees();
        }
    
        public class EmployeAccessLayer : IEmployeAccessLayer
        {
            private MyDbContext _context;
            public EmployeAccessLayer(MyDbContext context)
            {
                _context = context;
            }
    
            public IEnumerable GetAllEmployees()
            {
                try
                {
                    return _context.emps.ToList();
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
    }

    EmployeeController.css

    namespace BlazorServerApp.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class EmployeeController : ControllerBase
        {
            IEmployeAccessLayer _employeAccessLayer;
    
            public EmployeeController(IEmployeAccessLayer employeAccessLayer)
            {
                _employeAccessLayer = employeAccessLayer;
            }
    
            [HttpGet]
            [Route("Index")]
            public IEnumerable<Emp> Index()
            {
                return (IEnumerable<Emp>)_employeAccessLayer.GetAllEmployees();
            }
        }
    }

    GetEmployee.razor

    @page  "/employee"
    @inject HttpClient Http
    
    <h3>GetEmployee</h3>
    @code {
    
    }
    @if (empList == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class='table'>
            <thead>
                <tr>
                    <th>EmpID</th>
                    <th>EmpName</th>
                    <th>EmpCountry</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var emp in empList)
                {
                    <tr>
                        <td>@emp.empid</td>
                        <td>@emp.empname</td>
                        <td>@emp.empcountry</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        Emp[] empList;
        protected override async Task OnInitializedAsync() =>
            empList = await Http.GetJsonAsync<Emp[]>("employee/Index");
    }
    

    NavMenu.razor  //here I want to add emloyee link when user click employee then display the database data

    <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>

    Startup.cs

    namespace BlazorServerApp
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddServerSideBlazor();
                services.AddDbContext<MyDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));

    services.AddScoped<IEmployeAccessLayer, EmployeAccessLayer>();
    services.AddHttpClient("httpClient", client =>
    {
    client.BaseAddress = new Uri("https://localhost:44326/");
    }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>(); context.Database.EnsureCreated(); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); } } }

    but when I am run the project and write this line in address bar then give below error



    see my database image I have 2 record in table I want to display them in blazor

    see my blazor output

    hierarchy of myproject

    I want to display 2 record on that page in blazor?

    help

    Wednesday, August 26, 2020 7:16 AM

All replies

  • User-474980206 posted

    Because you registered a named client, a http factory is registered, not a client. Your inject should be a factory, see docs

       https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

    though it’s not clear why you are using an httpclient to call back to the same website. Why don’t you just inject a  IEmployeAccessLayer

    note: this is all razor page code, not blazor

    Wednesday, August 26, 2020 3:38 PM
  • User-91993069 posted

    if I am not writing httpclient then here give an error:

    @*@inject HttpClient Http*@
    
    @code {
                Emp[] empList;
    
                protected override async Task OnInitializedAsync()
                {
                    empList = await Http.GetJsonAsync<Emp[]>("employee/index");  //the name http does not exist in the current context
                }
        }

    this is all razor page code, not blazor  

    what do your means I am newbie in blazor

    Thursday, August 27, 2020 5:36 AM
  • User-474980206 posted

    As you are using server blazor, there is no need to make an http call to the same site.  You would use http if you where writing a WASM blazor api, or calling a different server. 

    as you registered a named httpclient, you must fetch by name, you can not inject it. Instead you inject a http factory, and call the factory to get the http client. Read the services docs, and http client docs, don’t just copy code, or if you do, only copy from one example. 

    also oninitalizedasync will fire twice, so you should check if the data call was already done.

    note: server blazor was just a stopgap, you really should be using client blazor.

    Thursday, August 27, 2020 5:31 PM
  • User-91993069 posted

    your means get method means(below code) call in blazor webassembly app(client side) project?

            [HttpGet]
            [Route("Index")]
            public IEnumerable<Emp> Index()
            {
                return (IEnumerable<Emp>)_employeAccessLayer.GetAllEmployees();
            }

    Friday, August 28, 2020 10:16 AM
  • User-91993069 posted

    Hello bruce

    thanks for your time

    I create another project webassembly client side project

    and then I create razor component

    GetRecordData.razor

    @page  "/employee/"
    @inject HttpClient Http
    <h3>GetEmployee</h3>
    
    @if (empList == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class='table'>
            <thead>
                <tr>
                    <th>EmpID</th>
                    <th>EmpName</th>
                    <th>EmpCountry</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var emp in empList)
                {
                    <tr>
                        <td>@emp.empid</td>
                        <td>@emp.empname</td>
                        <td>@emp.empcountry</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        Emp[] empList;
        protected override async Task OnInitializedAsync() =>
            empList = await Http.GetJsonAsync<Emp[]>("employee/Get");
    }

    EmployeeController.cs

    namespace BlazorServerApp.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class EmployeeController : ControllerBase
        {
            MyDbContext _myDbContext;
    
            public EmployeeController(MyDbContext myDbContext)
            {
                _myDbContext = myDbContext;
            }
    
            [HttpGet]
            [Route("Get")]
            public async Task<List<Emp>> Get()
            {
                return await _myDbContext.emps.ToListAsync();
            }
        }
    }
    

    but give an error:

    Friday, August 28, 2020 10:51 AM
  • User-474980206 posted

    The error means the website that blazor is calling threw an error. Use the browser network debugger to see the error. 

    Friday, August 28, 2020 3:14 PM
  • User-91993069 posted

    Hello beuce 

    thanks for support

    can you help more

    see webapi response is 200 ok

    when I am debugging I could not understood the error:

    what is error?

    Saturday, August 29, 2020 4:51 AM