Inject code into head from widget (MVC v 12SP)

Laura Frese asked on May 12, 2020 03:45

I have a widget that allows someone to enter some code for google tags on only specific pages. I need to inject some specific code into the head depending on the page the widget is placed on. You cant use sections with partial views. In my _Layout page, I have @RenderSection("head", false) in the head and on my widget view I have @section(Model.HeadCode) - this doesnt work. How would I make this work?

Recent Answers

Dmitry Bastron answered on May 12, 2020 10:22

Hi Laura,

Yes, you are right, by the time when execution comes to your widget, the head block is already rendered that's why sections don't work for you. I guess you have two options here:

  1. Hard one. In your widget code save the code you need to inject in head into request context and then use MVC Action Filters to post-process HTML and inject your code in head. You can use some custom placeholder and replace it with regex. I wouldn't recommend this approach too much, but if it is mandatory to be implemented as widget, I don't think you would have any other option then that.

  2. Easy one. Just do not use widgets for it. You can create a text field in your page types and place this optional code there instead. With this approach you can build a view model and withdraw it in layout directly.

To me this particular case looks like a slight misuse of widgets concept. Widgets are supposed to hold page content.

0 votesVote for this answer Mark as a Correct answer

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