不能在.ascx中使用“var”变量?

时间:2012-10-18 08:05:36

标签: c# .net

在.ascx.cs上我有这段代码,例如:

var xDoc = XDocument.Parse(xml); //or XDocument.Load(fileName)
var list =  xDoc.Descendants("ordinanza")
                .Select(n => new
                {
                    Numero = n.Element("numero").Value,
                    Titolo = n.Element("titolo").Value,
                })
                .ToList();

好吧,现在我想在我的.ascx上“预约”这个匿名类型,但我不能使用protected {public list(因为var)。

那么,我该怎么做呢?

1 个答案:

答案 0 :(得分:3)

您正在提取的数据是较大实体的缩减版本,您在视图中使用此数据。在MVC或MVP术语中,这将是一个视图模型(一种用于在UI中显示数据的数据传输对象)。

你可以做的是创建一个简单的轻量级类(视图模型)来保存这些数据:

public CustomerContactViewModel()
{
    public string Name { get; set; }

    public string Phone { get; set; }
}

然后将您的LINQ查询更新为:

IEnumerable<CustomerContactViewModel> custQuery =
    from cust in customers
    where cust.City == "Phoenix"
    select new CustomerContactViewModel() { Name = cust.Name, Phone = cust.Phone };