Search code examples
c#vieworchardcmsmodels

Overriding @Display


I've different model types that are subclasses of abstract model. I'm rendering it in that way:

<ul>
    @foreach(dynamic model in @Model.ModelList)
    {
        <li>
            @Display(model)
        </li>
    }
</ul>

How can I define "Display" for each type (I want to have different cshtmls for each model type)? I think it is connected with shapes. How can I define one shape and view for each type? Is this correct approach?


Solution

  • I've figured out the solution (it was not easy, because I'm totaly newbie if it is going about Orchard) Creating new shape:

        public void Discover(ShapeTableBuilder builder)
        {
            builder.Describe("MyModel").OnDisplaying(
                displaying =>
                    {
                        var elementObject = displaying.Shape;
                        var elementId = elementObject.Id;
                        elementObject.Metadata.Alternates.Add("MyModel__" + EncodeAlternateElement(elementId));
                    });
        }
    
        private string EncodeAlternateElement(string alternateElement)
        {
            return alternateElement.Replace("-", "__").Replace(".", "_");
        }
    

    Using it in a view:

    <ul>
    @foreach (var model in @Model)
    {
        <li>
    
            @Display(@New.MyModel(Id: model.Id, modelInstance: model))
    
        </li>
    }
    </ul>