Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hermanussen/1575f7d99575a1a492f949e9aeabd3dd to your computer and use it in GitHub Desktop.
Save hermanussen/1575f7d99575a1a492f949e9aeabd3dd to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Mvc.Pipelines.Response.GetModel;
using Sitecore.Mvc.Presentation;
using UnitTestingDemo.Website.Domain;
using UnitTestingDemo.Website.Models;
namespace UnitTestingDemo.Website.Pipelines
{
/// <summary>
/// This processor can be used in the mvc.GetModel pipeline to resolve the current CDM based model,
/// from the context item or the datasource (if defined).
/// The rendering must have the parameter 'typedmodel=1' defined, or else this processor will leave it alone.
/// </summary>
public class CreateTypedRenderingModel : GetModelProcessor
{
public override void Process(GetModelArgs args)
{
if (args.Result == null && "1".Equals(args.Rendering.Parameters["typedmodel"]))
{
args.Result = CreateTypedModel(args.Rendering);
}
}
/// <summary>
/// Uses reflection to create a CDM based model for a rendering
/// </summary>
/// <param name="rendering"></param>
/// <returns></returns>
protected virtual object CreateTypedModel(Rendering rendering)
{
Type targetType = ItemWrapper.GetTypeForTemplateId(rendering.Item.TemplateID);
var d1 = typeof(RenderingModel<>);
Type[] typeArgs = { targetType };
var makeme = d1.MakeGenericType(typeArgs);
return Activator.CreateInstance(makeme);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment