[英]Razor page ASP.NET displaying data with a stored procedure
我试图在加载页面时动态显示存储过程调用的结果。 我在 Page 模型的 for 循环中遇到了麻烦。 如何解决此问题,使其每列仅显示一次?
另外,我将如何显示作为 SQL Server 中“0x151C2F0002000000...” image
的图片
剃刀页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dynamic Display Sample</title>
<script></script>
</head>
<body>
<table>
@foreach (var SampleObject in Model.SampleObjectCollection)
{
<tr>
<td>@SampleObject.CategoryName</td>
<td>@SampleObject.Description</td>
<td>@SampleObject.Picture</td>
</tr>
}
</table>
</body>
</html>
班级
public class Categories
{
public string CategoryName { get; set; }
public string Description { get; set; }
public string Picture { get; set; }
}
页面模型
private List<Categories> _sampleObjectCollection = new List<Categories>();
public List<Categories> SampleObjectCollection
{
get
{
return _sampleObjectCollection;
}
}
public void OnGet()
{
SqlConnection MyDataSource = new SqlConnection();
MyDataSource.ConnectionString = @"Persist Security Info=False;
Database=Northwind;
User ID=***;
Password=***;
server=***;
TrustServerCertificate=true";
MyDataSource.Open();
SqlCommand GetCommand = new SqlCommand
{
Connection = MyDataSource,
CommandType = CommandType.StoredProcedure,
CommandText = "jhong14.GetNorthwindCategories"
};
Categories SampleObject;
SqlDataReader GetDataReader;
GetDataReader = GetCommand.ExecuteReader();
if (GetDataReader.HasRows)
{
while (GetDataReader.Read())
{
for (int Index = 0; Index < GetDataReader.FieldCount; Index++)
{
SampleObject = new Categories
{
CategoryName = GetDataReader[Index].ToString(),
Description = GetDataReader[Index].ToString(),
Picture = GetDataReader[Index].ToString()
};
SampleObjectCollection.Add(SampleObject);
}
}
}
GetDataReader.Close();
MyDataSource.Close();
}
SQL Server 存储过程:
CREATE PROCEDURE jhong14.GetNorthwindCategories
AS
BEGIN
SELECT CategoryName, Description, Picture
FROM Categories
ORDER BY CategoryName DESC
END
读取数据时出现错误,试试这个
if (GetDataReader.HasRows)
{
while (GetDataReader.Read())
{
SampleObject = new Categories
{
CategoryName = GetDataReader[0].ToString(),
Description = GetDataReader[1].ToString(),
Picture = GetDataReader[2].ToString()
};
SampleObjectCollection.Add(SampleObject);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.