I was trying to bind View Bag data to a HTML table. My C# code works fine. Can add data to View Bag as ViewBag.employeeData = getDBData();
but when i try to access each item,
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException is thrown.
Below given my C# code
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(); }
}
Razor
<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>
Exception:
'object' does not contain a definition for 'ID'.
How to resolve this?