Is it possible to databind using an anonymous type?
I think that's the right terminology...
Basically, I have a repeater control, and a Linq query that retrieves some items. Ordinarily I would databind straight to the query and use Eval to populate the template with the results.
However, it doesn't come through in quite the right format - for example, if EndDate is null (it's a DateTime?) then I want to substitute开发者_运维技巧 it with "Present". I am using only a couple of the properties in the query result objects.
I am wondering if there's a solution like:
[pseudo madeup code]
var query = getResults();
List<anonymous> anonList = new List();
foreach (var q in query)
{
string myEndDate = "";
if (q.EndDate.HasValue)
{ myEndDate = q.EndDate.ToString(); }
else
{ myEndDate = "Present"; }
anonList.items.add(new { name=q.name, enddate=myEndDate };
}
repeater.Datasource = anonList;
then
<div><%#Eval("enddate")%></div>
You have two options for declaring you result list:
- Use a non-generic
ArrayList
, or - Use
Enumerable.Repeat
, ie.var anonList = Enumerable.Repeat(new { name="", enddate=""}, 0).ToList();
Yes, you can bind against anonymous types but your code to generate the sequence of those types will have to change a bit:
repeater.DataSource
= getResults()
.Select(q => new {
name = q.name,
enddate = (q.EndDate.HasValue)
? q.EndDate.ToString()
: "Present"
});
You could take Andrews sample:
repeater.DataSource = getResults()
.Select(q => new {
name = q.name,
enddate = (q.EndDate.HasValue)
? q.EndDate.ToString()
: "Present" });
but instead of computing the enddate inline, you call a function:
repeater.DataSource = getResults()
.Select(q => new {
name = q.name,
enddate = GetEndDate(q)});
private void GetEndDate(TypeOfQ q)
{
return (q.EndDate.HasValue) ? q.EndDate.ToString() : "Present";
}
Is that what you ment??
regards, Chris
精彩评论