5

Issue: I want to add two accordion components to one page. The IDs are the same so both of the components will not work.

My Proposed Solution: Using MVC, add code to the component that will check if there is already an existing component of the same (accordion) type on the page. If so, start the incrementing of IDs at a different number. I would think that should solve the issue.

Is there an MVC way to check if a component has already been added to a page in Experience Editor?

Any help would be greatly appreciated!

  • 4
    The Model can have a property that returnsa unique ID string which can be bound to the view. Perhaps a standard prefix + Unique ID will work. e.g.: "accordion-CE675E37357D47C1853B81A90F93BE12", where the suffix is a sitecore shortid. – Nathan Hase Jun 29 '17 at 15:49
  • 1
    @NathanHase solution is what I would normally do. In case it's not obvious, I would make sure to use a class on the HTML element as well, and target all CSS rules and Javascript/jQuery calls against the class name. – Matthew FitzGerald-Chamberlain Jun 29 '17 at 16:11
  • 1
    Agreed, thanks @MatthewFitzGerald-Chamberlain. Something like class="this_is_my_accordion_selector". I would also make it a special selector classname that is not connected to style to keep the behavior separated. – Nathan Hase Jun 29 '17 at 16:14
  • 2
    @NathanHase you should add that comment as an answer - its a good solution to the problem! For a unique Id - you could use the rendering Id – Richard Seal Jun 29 '17 at 16:59
  • 1
    Thanks! This solution makes sense. I'm quite new to this though @RichardSeal, how would i pull the rendering ID? – Kizzie Jun 29 '17 at 17:16
6

Rather than dealing with the Layout via Sitecore, we can generate an ID string that will be unique for each instance of the component.

The Model can have a property that returns a unique ID string which can be bound to the view. Perhaps a standard prefix + Unique ID will work.

e.g.: id="accordion-CE675E37357D47C1853B81A90F93BE12", where the suffix is a sitecore shortid.

public class AccordionComponent
{
    public string ComponentId { get; private set; }

    public AccordionComponent()
    {
        var shortId = ID.NewID.ToShortID();
        ComponentId = $"accordion-{shortId}";
    }
}

And use the ComponentId property in the View like this:

<div id="@Model.ComponentId" class="accordion_selector_class">
    ...
</div>

Each accordion container element will have a common class that can be used to select all of them with javascript. This array of elements can then be used to apply the accordion behavior as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.