【问题标题】:can't access stored procedure values in foreach loop in asp.net mvc无法访问 asp.net mvc 中 foreach 循环中的存储过程值
【发布时间】:2026-02-19 01:30:01
【问题描述】:

无法访问foreach循环中存储过程的SQL select语句的列值
运行代码时出现此错误 enter image description here

这是存储过程

ALTER proc [dbo].[getAuthorBooks]
@id int
as
Begin
select BookName,Paid from Book where AuthorId=@id
End

这是 C# 代码 公共 ActionResult 编辑(int id) {

        Author auth = new Author();
        parhowDBEntities d=new parhowDBEntities();
        var data = d.getAuthorBooks(9).ToList();
        int x=data.Count;
        ViewBag.AB = data;

        Author auth2 = new Author();

        auth2 = auth.GetEntity(id);

        return View(auth2);
    }

这是查看代码

        @foreach (var item in ViewBag.AB)
        {
            @item.BookName
        }

【问题讨论】:

    标签: asp.net-mvc stored-procedures


    【解决方案1】:

    首先,您应该将 ViewBag.ViewBag.AB 转换为 List。然后您可以访问如下列:

    @foreach (var item in  (List<Author>)ViewBag.AB )
            {
                <td> @item.BookName </td>
            }
    

    【讨论】:

    • 我使用连接从多个表中获取数据,所以这不适合我。
    • 所以你可以创建一个具有所有你需要的属性的模型,我的朋友。然后,可以轻松访问。