This project is read-only.

Check for existence of field by name from within view...

Topics: Customizing Orchard
Sep 24, 2012 at 4:33 AM

I have a base theme that I use for all my tenants, in which I would like to over-ride the MenuItem.cshtml part to have it include a custom css class field.

This field is something in have manually added to some tenant's MenuItem part when I need to specify custom css (it's not neccesarily defined on the menu part for all tenants).

So in the MenuItem.cshtml in my base theme, I want to check that the menu part content item has a field named "CustomCss" before I attempt to access it. 

Is there a helper for this? Something like ContentItem.HasField("CustomCss")?

Sep 24, 2012 at 4:54 AM

if (Model.ContentItem.YourContentTypeName.CustomCss == null) ?

Sep 25, 2012 at 2:49 AM
Edited Sep 25, 2012 at 2:50 AM

Half of my problem was that I had added the "CssClass" text field to the "Custom Link" content type, rather than the "Menu" part (which is included in the Custom Link, HTML Menu Item & Content Menu Item content types).

After adding the field to the Menu part I can access it in the MenuItem.cshtml via @Model.Content.ContentItem.MenuPart.CssClass.Value

That said, I still have the situation where this partial view is in a base theme, and I may have a tenant that doesn't define the CssClass field on the menu part.

In the MenuItem.cshtml if I just try to check if its null as you suggested, I get the following exception:

Orchard.Core.Navigation.Models.MenuPart' does not contain a definition for 'CssClass'

So in the end I have added the following code to the partial view to iterate the fields on the parts...

    foreach (var field in Model.Content.ContentItem.MenuPart.Fields)
        if (field.Name == "CssClass")