2

我正在尝试按照 youtube tuturial 学习 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();
    }
   }

剃刀页面

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

 }

启动.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>();
    }
4

1 回答 1

3

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

与答案无关:

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

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

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

于 2020-01-05T01:06:02.510 回答