Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Bear 40 posts 129 karma points
    Sep 03, 2013 @ 17:14
    Bear
    0

    IPublishedContent to Strongly Typed Model / Custom View Model?

    Note that I'm using custom everything (custom MVC routes, custom controllers, custom view models etc. I'm not interested in using the default routing & controller per doctype).

    As I understand it, the ContentService should only be used for node manipulation and that for 'reading' I should be using UmbracoContext.ContentCache and the methods on there (e.g. GetSingleByXPath()) that return IPublishedContent. Is this correct?

    I have several strongly typed models set up BlogPost and StaffProfile, given that these inherit from RenderModel what is the best way to convert them to strongly typed models? or custom view models?

    For example a route that is /blog/authors/john-bear/ would list all blog posts by that author, using a custom view model;

    public class BlogPostAuthorViewModel
    {
        // properties 
        public StaffProfile StaffProfile { get; set; }
        public IEnumerable<BlogPost> BlogPosts { get; set; }
    
        // constructor
        public BlogPostAuthor() {
            BlogPosts = new List<BlogPost>();
        }
    }
    

    And in the controller...

    public ActionResult Author(string authorName)
    {          
         // create model to return
         var blogPostAuthorViewModel = new blogPostAuthorViewModel();
    
         // #TODO - fetch author and all blog posts                
    
         // finally pass back to view;
         return View("~/Views/Blog/BlogPostAuthor.cshtml", blogPostAuthorViewModel );
    }
    

    As I see it, there are myriad of ways to achieve the middle bit #TODO - fetch author and all blog posts. I could use Examine or XPath.

    For setting the author I could do;

    // get the id of the author
    var authorXpathQuery = String.Format("//StaffProfile[@nodeName='{0}']", authorName.Replace("-"," "));
    var publishedAuthor = umbracoContext.ContentCache.GetSingleByXPath(authorXpathQuery);
    if ( publishedAuthor != null )
    {
        // turn into render model
        var staffProfile = new RenderModel(publishedAuthor, CultureInfo.CurrentUICulture);
    
        // and into my custom strongly typed StaffProfile object
        var author = new StaffProfile(staffProfile.Content, staffProfile.CurrentCulture);
    
        // and add into the render model
        blogPostAuthorViewModel.Author = author;
    }
    

    Is this approach correct? Is there an easier way to do this?

Please Sign in or register to post replies

Write your reply to:

Draft