将 ViewBag 数据绑定到 HTML 表



我试图将View Bag数据绑定到HTML表。我的 C# 代码工作正常。可以ViewBag.employeeData = getDBData();将数据添加到 View Bag 中,但是当我尝试访问每个项目时,

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException 被抛出。

下面给出了我的 C# 代码

   private IEnumerable<Employees> getDBData()
    {
        SqlConnection con = null;
        Employees empData;
        string sqlConn = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
        try
        {
            using (con = new SqlConnection(sqlConn))
            {
                SqlCommand command = new SqlCommand("SELECT ID,FirstName,LastName,Gender,Salary FROM Employees", con);
                con.Open();
                SqlDataReader read = command.ExecuteReader();
                List<Employees> empDetails = new List<Employees>();
                while (read.Read())
                {
                    empData = new Employees();
                    empData.ID = Convert.ToInt32(read["ID"]);
                    empData.FirstName = Convert.ToString(read["FirstName"]);
                    empData.LastName = Convert.ToString(read["LastName"]);
                    empData.Gender = Convert.ToString(read["Gender"]);
                    empData.Salary = Convert.ToInt32(read["Salary"]);
                    empDetails.Add(empData);
                }
                return empDetails;
            }
        }
        catch (Exception)
        { return null; }
        finally { con.Dispose(); }
    }

剃刀

        <table class="table table-striped table-condensed">
        <thead>
            <tr>
                <th>ID</th>
                <th>FirstName</th>
                <th>LastName</th>
                <th>Gender</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in ViewBag.employeeData)
            {
                <tr>
                    <td>@item.ID</td>
                    <td>@item.FirstName</td>
                    <td>@item.LastName</td>
                    <td>@item.Gender</td>
                    <td>@item.Salary</td>
                </tr>
            }
        </tbody>
    </table>

例外:

"

对象"不包含"ID"的定义。

如何解决这个问题?

你不需要

使用ViewBag(我建议永远不要使用它)。 从控制器返回值时:

return empDetails;

它将成为视图模型。 在视图中,需要声明模型类型:

@model List<Employees>

然后,您可以:

@foreach (var item in Model)
{
  <tr>
    <td>@item.ID</td>
    <td>@item.FirstName</td>
    <td>@item.LastName</td>
    <td>@item.Gender</td>
    <td>@item.Salary</td>
  </tr>
}

剃刀如何知道持有从控制器类返回的列表。

这是 asp.net-mvc 的设计约定。 动态视图与强类型视图。

调试您的问题非常困难,因为您没有正确提供数据。但是您可以尝试这样做来从@foreach获取数据 -

@foreach (var item in Model.Foo.Foo1)
{
    @Html.DisplayFor(modelItem=> item.fooName)
}

并检查您正在迭代的所有项目,也许您错过了一些值,或者这可能是一个拼写错误

最新更新