You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET网页无法显示数据库内容,请求排查解决

数据库数据无法在Razor页面显示的排查方案

我跟着视频教程开发连接数据库的Web应用,将教程中的client替换为student后,浏览器仅显示表格框架,无法加载数据库内容。已完成添加System.Data.Sql依赖、创建并填充数据库等步骤,但数据仍未显示。


相关代码与信息

后端CS代码

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.SqlClient;

namespace assignment2.Pages.Students
{
    public class IndexModel : PageModel
    {
        public List<StudentInfo> listStudents = new List<StudentInfo>();
        public void OnGet()
        {
            try
            {
                String connectionString = "Data Source=.\sqlexpress;Initial Catalog=unicafschooldb;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";
                using (SqlConnection connection = new SqlConnection(connectionString)) 
                {
                    connection.Open();
                    string sql = "SELECT * FROM students";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                           while (reader.Read())
                            {
                                StudentInfo studentInfo = new StudentInfo();
                                studentInfo.id = "" + reader.GetInt32(0);
                                studentInfo.name =  reader.GetString(1);
                                studentInfo.email =  reader.GetString(2);
                                studentInfo.phone =  reader.GetString(3);
                                studentInfo.teacher =  reader.GetString(4);
                                studentInfo.course =  reader.GetString(5);
                                listStudents.Add(studentInfo);
                            }
                        }
                    }                                
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:" + ex.ToString());
            }
        }
    }
    public class StudentInfo
    {
        public string id;
        public string name;
        public string phone;
        public string email;
        public string teacher;
        public string course;
    }
}

问题现象

  • 页面仅展示表格结构,无表体数据
  • 数据库已填充对应学生数据

可能的错误点及解决方法

1. 连接字符串转义错误

C#字符串中反斜杠是转义符,原代码里的.\sqlexpress会被解析为.sqlexpress,导致无法正确连接SQL Server实例。
修复方案:
使用逐字字符串(加@前缀)或转义反斜杠:

// 方案1:逐字字符串
String connectionString = @"Data Source=.\sqlexpress;Initial Catalog=unicafschooldb;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";

// 方案2:转义反斜杠
String connectionString = "Data Source=.\\sqlexpress;Initial Catalog=unicafschooldb;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";

2. 依赖列顺序读取数据易出错

原代码通过索引(reader.GetInt32(0))读取数据,若数据库表students的列顺序与预期不符,会抛出异常,但异常被try-catch捕获后仅输出到控制台,无法直观看到。
修复方案:
改为按列名读取数据,避免依赖列顺序:

while (reader.Read())
{
    StudentInfo studentInfo = new StudentInfo();
    studentInfo.id = reader["id"].ToString();
    studentInfo.name = reader["name"].ToString();
    studentInfo.email = reader["email"].ToString();
    studentInfo.phone = reader["phone"].ToString();
    studentInfo.teacher = reader["teacher"].ToString();
    studentInfo.course = reader["course"].ToString();
    listStudents.Add(studentInfo);
}

3. 异常信息无法直观查看

原代码将异常输出到控制台,在Web应用中难以直接查看,无法快速定位问题。
修复方案:
在IndexModel中添加异常信息属性,在页面上展示:

public class IndexModel : PageModel
{
    public List<StudentInfo> listStudents = new List<StudentInfo>();
    public string ErrorMessage { get; set; } // 添加异常信息属性

    public void OnGet()
    {
        try
        {
            // 原连接与查询代码
        }
        catch (Exception ex)
        {
            ErrorMessage = ex.ToString(); // 保存异常信息
        }
    }
}

在CSHTML页面中添加异常展示代码:

@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
    <div style="color:red; padding:10px; border:1px solid red;">
        @Model.ErrorMessage
    </div>
}

4. Razor页面绑定错误

需确保CSHTML页面正确绑定listStudents集合,示例代码如下:

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>老师</th>
            <th>课程</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var student in Model.listStudents)
        {
            <tr>
                <td>@student.id</td>
                <td>@student.name</td>
                <td>@student.email</td>
                <td>@student.phone</td>
                <td>@student.teacher</td>
                <td>@student.course</td>
            </tr>
        }
    </tbody>
</table>

检查是否存在拼写错误(如字段名大小写不一致)、未遍历Model.listStudents等问题。


内容的提问来源于stack exchange,提问作者Fabian Shamano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:13:16