Databinder.Eval of object inside object

时间:2015-10-06 08:47:35

标签: c# asp.net data-binding

How would I retrive the info of an object inside my object using the Databinder.Eval method?

The class I'm trying to get the object name from looks like

public class Festival
{
    public int id { set; get; }
    public string name { set; get; }
    public DateTime date_start { set; get; }
    public DateTime date_end { set; get; }
    public City city;
}

(The city object has an a string called name)

And the code I'm trying to get working is

<td><%# DataBinder.Eval(Container.DataItem, "city.name") %></td>

Thanks.

1 个答案:

答案 0 :(得分:1)

For a quick hack, try writing a helper method in code behind like:

protected string GetCityName(object o)
{
    var c = o as City;
    if(c==null)
        return "Invalid Object";//YOU CAN RETURN EMPTY OR DO SOMETHING ELSE

    return c.name;
}

aspx:

<%# GetCityName(Eval("city"))%>

Or you can have string property in your Festival class that returns City.Name like:

public string CityName{get{return city.name;/*Check for null*/}}

Or better still have a view model exposing exactly the properties that you need and the way you want them.