开发者

asp.net mvc - multiple databound components on a page

Im new to asp.net mvc and just learning the basics right now.

Im wondering how pages with muliple databound items would work with mvc views.

for example say there is a page that list开发者_StackOverflows a bunch of "news articles" from a "NewsArticles" table. and in the side of the page there is a another list which contains a list of "CaseStudies" for example.

then how would that be achieved in mvc?


You'd create your own view model class:

public MyPageViewModel
{
  public IEnumerable<NewsArticles> Articles{get;set;}
  public IEnumerable<CaseStudies> CaseStudies{get;set;}
}

Return it as the model in your action:

public ActionResult MyPage()
{
   var model = new MyPageViewModel();
   model.Articles = ArticleManager.GetArticles();
   model.CaseStudies = CaseStudyManager.GetCaseStudies();
   return View(model);
}

Then you can use a strongly typed view of type ViewPage<MyPageViewModel>, and output them like this:

<ul>
<% foreach(NewsArticle article in Model.Articles){%>
<li><%=article.Title%></li>
<%}%>
</ul>

<ul>
<% foreach(CaseStudy caseStudy in Model.CaseStudies){%>
<li><%=caseStudy.Title%></li>
<%}%>
</ul>


One option would be to specify the ViewData in the action method:

ViewData["NewsArticles"] = GetNewsAticles();
ViewData["CaseStudies"] = GetCaseStudies();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜