MVC3局部视图 [英] MVC3 Partial Views
问题描述
还在学习MVC3,EF。现在我连接到MySQL,但我相信不会是相关的。为简单起见,我决定使用一个数据库,为我的测试应用程序,我已经包括一个类别来区分数据。对于如我有一个新闻,活动,信息和页面类别。现在,当它涉及到在网页的意见,例如上市的内容,我想列出最新的5新闻项目(新闻类),最新的5个事件(事件类别),欢迎文字(信息类)。我已经能够创建partialViews在网页的不同部分列出这些。但我觉得我做这个错误,因为在这些PartialViews的,我一遍又一遍地查询相同的表,只是用,其中猫= ....
中的LINQ查询过滤。
能否请您确认是否应该是这样的做法或有更好的方法来做到这一点。
Still Learning MVC3, EF. For now I am connecting to MySql but I believe that will not be relevant. For simplicity, I decided to use one database for my test application and I have included a category to differentiate the data. For eg I have a news, events,info and pages categories. Now when it comes to listing contents in views for example at the homepage, I want to list latest 5 news items(news category), latest 5 events(events category), welcome text(info category). i have been able to create partialViews to list these at the different sections of the homepage. But I feel am doing this wrongly since in each of these PartialViews I am querying the same table over and over and just filtering with where cat=....
in the LINQ query.
Can you please confirm if that should be the practice or there is a better way to do this.
推荐答案
您可以做到以下几点:
控制器:
public ActionResult Home()
{
IEnumerable<MyDateRecords> myData = LinqQueryToGetAllTheDataUnFiltered();
ViewData.Model = new MyViewData { MyData = myData; }
return View();
}
ViewModel类:
ViewModel class:
public class MyViewData
{
List<MyDataRecords> MyData { get; set; }
List<MyDataRecords> News { get { return MyData.Where(m => m.Category = "News"); } }
List<MyDataRecords> Events { get { return MyData.Where(m => m.Category = "Events"); } }
}
查看:
@model MyViewModel
@Html.Partial("NewsPartial", Model.News)
@Html.Partial("EventsPartial", Model.Events)
部分:
@model IEnumerable<MyDataRecord>
这样,我们只查询了一次数据,并刚刚通过一组不同的每一个部分。
This way we only queried for the data once and just passed a different set to each partial
这篇关于MVC3局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!