Retrieve data from widgets in MVC editable area

Jon Tetzlaff asked on August 20, 2019 14:42

I have a MVC template that has a page builder editable area in it @Html.Kentico().EditableArea("steps", "MVC.Components.RecipeSteps", new string[] { "MVC.Widget.RecipeStep" })

It is limited to a single widget that turns into the steps for a recipe. You can add as many steps as you want, which is exactly how I wanted it to work.

I'd like to be able to pull out the model data from the widgets that go into that editable area and display it elsewhere on my template. Google has a recipe structured data example for SEO that needs to have a recipes steps displayed in it as an array, but that widget data is unavailable to me currently. Anyone have any ideas on how to get it?

{ "@context": "https://schema.org/", "@type": "Recipe", "name": "Schema example", ... "recipeInstructions": [ { "@type": "HowToStep", "text": "I'd like to put my widget data here." } ], ... }

Correct Answer

Dmitry Bastron answered on August 20, 2019 15:26

Hi Jon,

I would do the following.

Create some small request context element with interface:

public interface IRecipeContext
{
    List<string> Steps {get; set;}
{

public class RecipeContext : IRecipeContext
{
    List<string> Steps {get; set;}

    public RecipeContext()
    {
        Steps = new List<string>();
    }
}

Register it with your favourite IoC container with per-request lifetime:

builder.RegisterType<RecipeContext>()
    .AsImplementedInterfaces()
    .InstancePerRequest();

So that you can access this context from you widget via dependency injection and write something in this context (in your example it will be some step data).

Then, you can also inject this context into your template controller and pass into view. But make sure rendering of your structured data goes after editable area. Otherwise this context will be empty.

2 votesVote for this answer Unmark Correct answer

   Please, sign in to be able to submit a new answer.