Try our conversational search powered by Generative AI!

Wrapper for Html.PropertyFor.


Our front end has asked for some sort of wrapper/extension method for the Html.PropertyFor() and the likes, that better represent whats being done. My idea is to probably write our own extension method to be used like "@Html.MyExtensionMethod(x => x.CurrentPage.SomeProperty);", but basically has the same logic behind it. It feels a bit cumbersome and not very DRY-friendly. Would there be a better way to go on about this? 

Feb 09, 2024 14:33

As an alternative, if you're using a newer version of the CMS and you're after something a bit more front-end friendly, it would be worth considering tag helpers. They can make it a bit more obvious what you're going to get when a property is rendered. For example, to write a heading to a page, you could use PropertyFor() like this:

@Html.PropertyFor(x => x.Heading, new { CustomTag = "h1", CssClass="heading-lv1"})

or you could use a tag helper like this:

<h1 class="heading-lv1" epi-property="Heading" />

You can read about tag helper usage here:

Feb 09, 2024 16:23
SebRom - Feb 12, 2024 10:53
Hi Paul, thanks for the input about tag helpers. This might be something we'll look into later.
There was a miss-communication about what was actually asked for, and I have now gotten a more clear view about the issue at hand. Consider the following scenario:
We have a block, with a view and some props. One of those props is a CTA button that has a partial view for its template. The button will be used all over the site.
On each block they would have to call: "@Html.RenderPartialAsync("path/to/buttonTemplate.cshtml", Model.CurrentBlock.Button) and instead would like:

But before I create my own custom class that might implement this, I just what to make sure there's no built in functionality for this?
Paul Gruffydd - Feb 12, 2024 12:25
If the CTA button is a property with its own view that's used in various places across the site, I'm assuming it's defined as a block property. If so, you should be able to render it like this:
SebRom - Feb 12, 2024 13:50
It is not defined like a block property at the moment. But this wrapper is supposed to handle more types. Let's say it handles 30 different types.
I agree with you that block properties are not a bad idea, and you could probably name those properties to make it more clear of what they actually render e.g @Html.PropertyFor(x => x.CurrentBlock.MyNamedProperty)? All the wrapper would negate is not having to write the path to a view X times, which having the different types as block properties solves anyway. Is there any downside in having an extensive amount of block properties used like that?
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.