【问题标题】:how to display list page in blazor如何在 blazor 中显示列表页面
【发布时间】:2020-08-26 05:57:21
【问题描述】:

我正在使用 blazor 中的 codefirst 方法,并且使用 code first 方法成功创建了 mydatabase

首先我创建一个项目,然后选择一个 Visual Studio 2019 -> blazor 应用程序 -> blazor 服务器应用程序

为什么我的员工列表页面没有在 blazor 中呈现

我想在 blazor 中显示 emp 表记录,但问题不是渲染

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("api/Employee/Index")]
        public IEnumerable<Emp> Index()
        {
            return (IEnumerable<Emp>)_employeAccessLayer.GetAllEmployees();
        }
    }
}

GetEmployee.razor

@*@page "/employee/GetEmployee"*@
@*@page  "/employee"*@
@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;
}

NavMenu.razor

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

查看我的数据库图像 我在表中有 2 条记录我想在 blazor 中显示它们

查看我的 blazor 输出

我的项目的层次结构

在这里给这个没什么地址发消息抱歉

编辑: 我在 GetEmployee.razor 中添加了这一行

@code {
    Emp[] empList;
    protected override async Task OnInitializedAsync() =>
        empList = await Http.GetJsonAsync<Emp[]>("api/Employee/Index");
}

但是当我运行项目并在地址栏中写下这一行时,会出现以下错误

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")));
        }

        // 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");
            });
        }
    }
}

【问题讨论】:

  • 我看不到,在您的页面中,您实际上调用了控制器的方法来检索列表以将某些内容放入empList
  • @AdrianoRepetti 实际上调用控制器的方法来检索列表以将某些内容放入 empList 是的,我想在主页上显示该数据
  • 为什么要为您的 blazor 服务器应用程序提供一个 rest-api?您可以在代码部分中使用注入的 DbContext 直接查询数据库。
  • @PinBack 你能提供参考吗

标签: c# visual-studio-2019 blazor blazor-server-side


【解决方案1】:

为什么要为您的 blazor 服务器应用程序提供一个 rest-api? 您可以在代码部分中使用注入的 DbContext 直接查询数据库。

您将 dbcontext 添加到服务集合 (ConfigureServices)。 现在您可以在代码部分中使用这些上下文:

@page  "/employee/"
@using Microsoft.EntityFrameworkCore;
@inject MyDbContext Context

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

    private List<Emp> empList;

    protected override async Task OnInitializedAsync()
    {
        this.empList = await Context.emps.ToListAsync();
    }
}

【讨论】:

  • 看到这张图片我正面临这个错误i.stack.imgur.com/xWo3e.pngSeverity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'SqlServerContext' could not be found (are you missing a using directive or an assembly reference?) BlazorServerApp C:\Users\FrontTech\source\repos\BlazorApp\BlazorServerApp\Pages\GetEmployee.razor 1 Active
  • 查看更新 SqlServerContext -> MyDbContext
  • 不明白不使用http请求数据都是get?
  • 我认为在使用 webassembly 应用程序发送请求时使用 http?
  • 您使用 Blazor 服务器端。这与 WebAssembly 无关。这种应用程序通过 WebSockets (SignalR) 与服务器通信。有很多资源解释了服务器端和 WASM 之间的区别。
【解决方案2】:

您忘记调用您的 API 请参阅 the docs

  protected override async Task OnInitializedAsync() => 
        empList= await Http.GetFromJsonAsync<Emp[]>("api/Employee/Index");

另外,记住你的页面方向必须是localhost:44326/employee

【讨论】:

  • 检查文档,可能你忘记包含@using System.Net.Http 或更多
  • 我添加了这个未解决的错误@using System.Net.Http
  • 安装此Install-Package Microsoft.AspNetCore.Blazor.HttpClient -Version 3.1.0-preview4.19579.2 后错误消失,但页面未呈现
  • 当我写这个localhost:44326/employee然后得到这个错误i.stack.imgur.com/zSpC6.png
【解决方案3】:

HttpClient 未在 Startup.cs 中注册为服务,这是我想到此问题 https://i.stack.imgur.com/zSpC6.png 的原因。

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<HttpClient>();
  .....
}

【讨论】:

【解决方案4】:

在配置服务方法的启动类中,您应该有以下内容:

 services.AddHttpClient("httpClient",client => 
 {
    client.BaseAddress = new Uri("https://localhost:44326/");
 });

或者如果你关注documentation:

services.AddScoped(sp => 
  new HttpClient
  {
   BaseAddress = new Uri("https://localhost:44326/")
  });

您的控制器路由不正确。

如果您的控制器上有[Route("api/[controller]")],您只需要在您的方法上方使用[Route("Index")]

您在代码中使用它的方式是 api 路由正在寻找 api/Employee/api/Employee/Index

将您的 api 代码更改为:

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

我个人更喜欢像这样使用GetAsync(...)

protected override async Task OnInitializedAsync()
{    
    var response = await Http.GetAsync("api/employee/index", HttpCompletionOption.ResponseContentRead);
    if (response.IsSuccessStatusCode)
    {
      empList = await JsonSerializer.DeserializeAsync<Emp[]>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });      
    }
    else                
      empList = new List<Emp>();
}

这样您可以获得更多关于调用 api 失败原因的信息。

【讨论】:

  • 当我写你的代码然后给出一个编译时错误见图片i.stack.imgur.com/6SH2L.png
  • 我想在那个页面上的员工中添加链接,当我点击员工时,默认打开索引页面
  • 看这张图片i.stack.imgur.com/bGHYj.png我改变了你说的所有东西都没有在那个页面上显示数据库数据
  • 我觉得你应该花点时间学习如何使用web api,然后再学习blazor。你的控制器不正确。我会再次更新代码..
  • YouTube 上关注此频道或通过Microsoft Documentation 开始
猜你喜欢
  • 2021-12-25
  • 2021-08-16
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
相关资源
最近更新 更多