简体   繁体   English

从 aspx 访问代码隐藏上的列表元素

[英]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然后在我的 aspx 上,我有以下 html 和 C# 代码

<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. PD:如果我将 item.Name 更改为 item,我可以正确地看到我的整个列表。

This is the expected behavior.这是预期的行为。 Note the return type of the method Exec , it is object .注意方法Exec的返回类型,它是object This type has not any property called Name .此类型没有任何名为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 .您需要将此返回类型更改为具有您要使用的属性Name的对象,或者仅返回List<string> ,如果您要使用的唯一属性是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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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