LINQ匿名类型+ MVC意见 [英] LINQ Anonymous Types + MVC Views
问题描述
我见过这个很多问题,但我从来没有真正得到我需要的答案。
I've seen many questions about this, but i've never really got the answer that I need.
我把从Web窗体一个相当大的web应用MVC和一段时间后,我encountred与将数据传递到视图的问题。在操作我执行code:
I'm converting a fairly large web application from Web Forms to MVC and after a while I encountred a problem with passing data to the view. In the Action I execute the code:
//这只是一个例子
计算机[QProducts] =从db.Products p选择新的{名称= p.Name,日期= p.ToShortDateString()}
计算机[QUsers] =从u在db.Users选择U;
我使用foreach循环遍历HTML中的对象,像这样的:
I use a foreach loop to iterate over the objects in html, like this:
foreach(var q in (IEnumerable)ViewData["QEvents"])
{
/*Print the data here*/
}
使用MVC之前,我只使用了 ASP:直放站
,但由于这是MVC我不能使用ASP.NET控件。
Before using MVC I just used a asp:Repeater
, but since this is MVC I can't use ASP.NET controls.
我怎样通过这些数据来查看?我真的没有不使用匿名类型这里的选项。 <%#ViewData.Eval()%>
显然是行不通的。
How am I supposed to pass this data to the View? I don't really have the option of not using Anonymous Types here. <%#ViewData.Eval()%>
obviously won't work.
任何想法?
推荐答案
而不是匿名类型,创建一个类型来保存名称和日期:
Rather than an anonymous type, create a type to hold the name and date:
public class NameDate
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
然后用在你的Linq查询:
Then use that in your Linq query:
from p in db.Products select new NameDate { Name = p.Name, Date = p.Date }
强烈键入您的看法是 MyView的&LT; IEnumerable的&LT; NameDate&GT;&GT;
,然后就做了的foreach(在ViewData.Model VAR nameDate) ...
这篇关于LINQ匿名类型+ MVC意见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!