Reputation: 841
I have the following method on codebehind
Public List<object> Exec()
{
List<object> result = New List<object>();
DataTable results = New DataTable();
// methodToExecuteSP is = public DataSet
results = methodToExecuteSP;
foreach (DataRow i in results.Rows)
{
result.Add(new { Name = i[“Name”] });
}
return result;
}
Then on my aspx I have the following html and C# code
<tbody>
<% foreach (var item in Exec()) { %>
<tr><td><%=item.Name %> </td></tr>
<% } %>
</tbody>
This shows the following error message:
Object does not contain a definition for Name.
What I’m doing wrong?
PD: If I change item.Name to item I can see my entire list properly.
Upvotes: 1
Views: 36
Reputation: 53958
This is the expected behavior. Note the return type of the method Exec
, it is object
. This type has not any property called Name
. That you need is to change this return type to an object with the property you want to use, Name
or to just return a List<string>
, if the only property you are going to use is the Name
.
first approach:
public class Person
{
public string Name { get; set; }
}
public List<Person> Exec()
{
var persons = new List<Person>();
var results = New DataTable();
// methodToExecuteSP is = public DataSet
results = methodToExecuteSP;
foreach (DataRow row in results.Rows)
{
result.Add(new Person { Name = row[“Name”].ToString() });
}
return persons;
}
<tbody>
<% foreach (var person in Exec()) { %>
<tr><td><%=person.Name %> </td></tr>
<% } %>
</tbody>
second approach:
public List<string> Exec()
{
var names = new List<string>();
var results = New DataTable();
// methodToExecuteSP is = public DataSet
results = methodToExecuteSP;
foreach (DataRow row in results.Rows)
{
result.Add(row[“Name”].ToString());
}
return names;
}
<tbody>
<% foreach (var name in Exec()) { %>
<tr><td><%=name%> </td></tr>
<% } %>
</tbody>
Upvotes: 1