asp.net mvc - Is there a design pattern to standardise the display of multiple models into a single view? -


i've tinkered derived classes, interfaces , viewmodels, haven't been able create quite need.

say we're building cms following models:

articleitem

  • title

  • summary

  • content

newsitem

  • headline

  • publishdate

  • summary

  • content

eventitem

  • eventtitle

  • startdate

  • enddate

  • content

i'm looking way standardise display of these 1 format / view (e.g. can display them in same rss feed). standardized view might called htmlitem , have 3 fields:

  • title

  • summary

  • content

the articleitem translate directly htmlitem, that's straightforward.

for newsitem join publishdate , first 100 characters of content create summary field of htmlitem.

for eventitem combine startdate , enddate create summary field of htmlitem.

ultimately i'm looking easiest, efficient way able pass 3 models single view has been designed display htmlitem. best shot far has been create 'convertor' class each model, can't feeling there better way this.

any experience, expertise , advice appreciated!

make viewmodel standarized properties , constructor each specialized class:

public class htmlitemviewmodel {     //properties     public string title {get; set;}     public string summary {get; set;}     public string content {get; set;}      //constructor inside htmlitemviewmodel each 1 of specialized classes:     public htmlitemviewmodel(articleitem item)     {         this.title = item.title;         this.summary = item.summary;         this.content = item.content;     }      public htmlitemviewmodel(newsitem item)     {         this.title = item.headline;         this.summary = string.format("{0} - {1}", item.publishdate, item.summary.substring(0,1000));         this.content = item.content;     }      public htmlitemviewmodel(eventitem item)     {         this.title = item.eventtitle;         this.summary = string.format("{0} - {1}", item.startdate, item.enddate);         this.content = item.content;     } } 

then, on method use rss feed pass each entity constructor on each individual query. this:

//example controller public class rsscontroller : controller {     public actionresult getrssfeed(){         //assuming have service each item type         var articlelist = articleservice.getarticles().select(s => new htmlitemviewmodel(s));         var newsitemlist = newsitemservice.getnewsitems().select(s => new htmlitemviewmodel(s));         var eventitemlist = eventitemservice.getevents().select(s => new htmlitemviewmodel(s));          articlelist.addrange(newsitemlist);         articlelist.addrange(eventitemlist);          return articlelist;     } } 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -