Home > Software engineering >  I have my data inside a SqlDataReader and i passed it to the html View, how can i work with that inf
I have my data inside a SqlDataReader and i passed it to the html View, how can i work with that inf

Time:03-22

I'm developing a scholl project(using asp.net core Web Application) and i select data from a sql server database using a stored procedure into a SqlDataReader, that returns that enter image description here

enter image description here

CodePudding user response:

It seems you want use SqlDataReader in razor page directly. Like below

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

As we know, we can get datas from SqlDataReader, and enter image description here

Please check the sentence in the image.

Because the effect displayed on your front-end page still needs to be calculated, I recommend that you create a new DataTable, and then adjust the data according to the business, and then pass the DataTable to the front-end. This is a better way to implement it.

//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);

Your cshtml should like below:

@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>

You need fill in data by yourself.

enter image description here

  • Related