简体   繁体   中英

Access to list element on codebehind from aspx

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM