【问题标题】:Sorry, there's nothing at this address page displaying when i clicked on the link using C# Blazor [closed]抱歉,当我使用 C# Blazor 单击链接时,此地址页面上没有显示任何内容 [关闭]
【发布时间】:2020-01-04 23:55:58
【问题描述】:

我正在尝试按照 youtube 教程学习 Blazor。我想使用下面的代码显示学生列表。当我点击学生链接时,我看到“对不起,这个地址什么都没有”。请问谁能告诉我哪里出错了

导航栏

    <li class="nav-item px-3">
        <NavLink class="nav-link" href="Pages/Student">
            <span class="oi oi-list-rich" aria-hidden="true"></span> Student data
        </NavLink>
    </li>

学生管理员

    public class StudentController : ControllerBase
    {
    private readonly RazorExampleContext _context;

    public StudentController(RazorExampleContext context)
    {
        _context = context;
    }
    // GET: api/Student
    [HttpGet]
    public async Task<ActionResult<List<Student>>> GetStudent()
    {
        return await _context.Student.ToListAsync();
    }
   }

RaZor 页面

 @page "/Student"
 @inject HttpClient Http
  // Display student list    
  <table class="table">
    <thead>
        <tr>
            <th></th>
            <th>Student Id</th>
            <th>Student Name</th>               
        </tr>
    </thead>
    <tbody>
        @foreach (var student in students)
        {
        <tr>
            <td>

                <a class="btn btn-success" href="Student/">Edit</a>
                <button class="btn btn-danger">Delete</button>

            </td>
            <td>student.Id</td>
            <td>student.StudentName</td>
        </tr>
        }
    </tbody>
   </table>
  }
  @code {
       Student[] students { get; set; }
   protected override async Task OnInitializedAsync()
   {
       await LoadStudent();
   }
  async Task LoadStudent()
  {
    students = await Http.GetJsonAsync<Student[]>("api/Student");
  }

 }

Startup.cs

 // 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
 public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddHttpClient();
        services.AddSingleton<WeatherForecastService>();
        services.AddSingleton<Student>();
    }

【问题讨论】:

标签: c# blazor asp.net-blazor


【解决方案1】:

当路由器找不到提供给它的url地址时,通常会发生此错误。改变这个:&lt;NavLink class="nav-link" href="Pages/Student"&gt;&lt;NavLink class="nav-link" href="student"&gt;

与答案无关:

  • 你为什么要这样做:services.AddSingleton&lt;Student&gt;();Student 是你的模型,而不是你要注入到组件中的服务

  • 在 foreach 循环中使用 Student 数组之前,应验证其是否已填充数据,否则会触发空引用异常。

  • 按照惯例,路由模板应该是@page "/student" 而不是@page "/Student"。

【讨论】:

  • 感谢您的回复我做了您要求的更改,但现在我遇到错误“InvalidOperationException:无法为类型'StudentProject.Pages.Student.Student'的属性'Http'提供值。那里没有“System.Net.Http.HttpClient”类型的注册服务。”
  • 在我的情况下,问题是由于某些奇怪的原因,.blazor 文件将 Build Action 设置为“None”而不是“Content”。我将其更改为“内容”并且它起作用了
猜你喜欢
  • 2022-07-19
  • 2022-07-23
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2022-01-19
相关资源
最近更新 更多