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

ASP.NET MVC中用View展示日志详情报错,求排查原因

异常原因排查及修复方案

核心问题分析

你的代码存在以下关键问题,直接引发运行时异常:

  1. Action未向View传递有效模型:执行存储过程后仅获取了DataReader,但未将数据映射到GetLogs模型集合,也未把模型传递给View,View遍历Model时会触发空引用异常。
  2. 数据库资源未正确释放:未使用using语句管理MySqlConnection、MySqlCommand和MySqlDataReader,会导致数据库连接泄漏。
  3. View未声明强类型模型:View需要遍历模型集合,但未指定强类型,Razor无法识别Model的具体类型,引发语法或运行错误。

分步修复代码

1. 修正Action方法

将DataReader数据映射到GetLogs集合,用using自动释放资源,并将模型传递给View:

public ActionResult GetLogs()
{
    string cnnString = ConfigurationManager.ConnectionStrings["DbConnString"].ConnectionString;
    var logs = new List<GetLogs>();

    using (MySqlConnection cnn = new MySqlConnection(cnnString))
    using (MySqlCommand cmd = new MySqlCommand("Get_AccessLog", cnn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cnn.Open();
        
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                logs.Add(new GetLogs
                {
                    LogActivityId = reader.GetInt32("LogActivityId"),
                    LogActivityName = reader.GetString("LogActivityName"),
                    LogActivityDesc = reader.GetString("LogActivityDesc")
                });
            }
        }
    }
    
    return View(logs);
}

2. 修正View的强类型声明

在View最顶部添加强类型模型声明(替换为你的模型命名空间):

@model IEnumerable<YourProjectNamespace.Models.GetLogs>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.LogActivityId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LogActivityName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LogActivityDesc)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.LogActivityId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LogActivityName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LogActivityDesc)
        </td>
    </tr>
}
</table>

3. 额外验证项

  • 确认log_activity表字段类型与GetLogs模型属性类型完全匹配(如LogActivityId为int类型)。
  • 检查Web.config中DbConnString连接字符串配置正确,可正常连接MySQL数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:43:33