我的数据位于 SqlDataReader 中,并将其传递给 html 视图,我如何在视图中处理该信息,并将其显示到 table 中?

I have my data inside a SqlDataReader and i passed it to the html View, how can i work with that info inside the view, and display it into a table?

我正在开发一个 scholl 项目(使用 asp.net 核心 Web 应用程序),我 select 使用存储过程将来自 sql 服务器数据库的数据导入 SqlDataReader,returns 即 The return of the stored procedure.

我已经将该 SQLDataReader 传递到我的 html 视图,现在我需要将该数据显示到 html table 中,如下所示:Table edited in paint to get the desired result,我是没有得到我想要的结果,因为我无法正确处理数据。

这就是我执行存储过程的方式。

   SqlCommand cmd = new SqlCommand("tentativa1", conn);
   cmd.CommandType = System.Data.CommandType.StoredProcedure;
   cmd.Parameters.Add(new SqlParameter("@tempo", "day"));
   cmd.Parameters.Add(new SqlParameter("@ap_id", "18"));
   SqlDataReader rdr = cmd.ExecuteReader();

这是我用来将 SqlDataReader 传递给视图的代码:

    public class MyViewModel
        {
            public List<teste> objteste { get; set; }
            public SqlDataReader rdr { get; set; }
            public List<L_AccessPoint> objAcessPoint { get; set; }
        }

这就是我用来“捕获”传递给视图的数据的代码: @model MyViewModel

我不知道使用 SqlDataReader 是处理数据的最佳方式还是使用其他方式更好。

如果你能帮我显示出想要的结果,我将不胜感激。

您似乎想直接在 razor 页面中使用 SqlDataReader。喜欢下面

@model MyViewModel
...
// This way is wrong.
Model.rdr

我们知道,我们可以从 SqlDataReaderthe datas should be filled in DataSet or DataTable.

获取数据

所以我的建议是你可以 refer my sqlheler to get datatable data by query or StoredProcedure

然后你会在你的方法中得到一个数据表,我模拟了一些与你提供的相同的数据。

请检查图片中的句子。

因为你front-end页面显示的效果还需要计算,建议你新建一个DataTable,然后根据业务调整数据,然后通过将 DataTable 添加到 front-end。这是一个更好的实现方式。

//MyViewModel model = new MyViewModel();
//model.DataObj= ToListByDataTable<DataModel>(dtSource);
DataTable dtYear = new DataTable();
DataView dvYear = dtSource.DefaultView;
dtYear = dvYear.ToTable(true,"year");

DataTable dtShow = new DataTable();
dtShow.Columns.Add("Ap_Name", typeof(String));
for (int i = 0; i < dtYear.Rows.Count; i++)
{
    dtShow.Columns.Add(dtYear.Rows[i]["year"].ToString(), typeof(String));
}
// Fill data into the DataTable of dtShow according to certain rules.

return View(dtShow);

您的 cshtml 应该如下所示:

@using System.Data
@model List<DataTable> 
<style>
    table, th, td {
        border: 1px solid;
    }
</style>

<table cellpadding="0" cellspacing="0">
    <tr>
        <th>Ap_Name</th>
        @foreach (DataRow row in Model[0].Rows)
        {
            <th>@row["year"]</th>
        }
    </tr>

    @foreach (DataRow row in Model[1].Rows)
    {
        <tr>
            <td>@row["Ap_Name"]</td>
             @foreach (DataRow row1 in Model[0].Rows) { 
                 <td>@row1["year"]</td>
             }
        </tr>
    }
</table>

需要自己填写数据