Search code examples
c#umbraco

Modify IPublishedContent properties in Umbraco custom controller


First of all, I realise that the core of my problmen probably is the way that I'm trying to solve it, so let me first explain what I'm trying to do.

I have a Layout where I output a property.

Layout.cshtml

inherits Umbraco.Web.Mvc.UmbracoTemplatePage
...
//More of the layout here

<title>@Model.Content.GetPropertyValue("title")</title>

...

This is the base of the other templates:

FullWidth.cshtml

@{ Layout = "Layout.cshtml"; }
... layout here

This all works well, I make sure every document type has a property called title and it gets printed all the time.

Now I'm creating a page, where some data from a database is being displayed. So I created a custom controller:

public class ProductController : RenderMvcController
{
    public ActionResult Index(Rendermodel model, int id)
    {
          var viewModel = new CustomRenderModel(model.Content);
          viewModel.Product = Database.GetProductById(id);
          return CurrentTemplate(viewModel);
    }

}

This works great too, but the next thing I want to do is also set the title based on whatever is retrieved from the database. Something like this:

var viewModel = new CustomRenderModel(model.Content);
var product = Database.GetProductById(id);
viewModel.Product = product;
viewModel.Content.SetPropertyValue("title", product.name");

Obviously this doesnt work because the IPublishedContent is readonly. I'm just wondering what the best way is to modify a property like that.

I realise that exposing a SetPropertyValue is a bad idea probably, but what would be the way to solve this.


Solution

  • I would render this title in a separate partial view and give that partial view a specific model to render.

    Have a look at this blog post I wrote which shows you how to do that. http://www.codeshare.co.uk/blog/how-to-optimise-your-website-for-search-engines-seo-in-umbraco/

    Kind regards

    Paul