Last active
April 13, 2017 04:32
-
-
Save richardszalay/5088286 to your computer and use it in GitHub Desktop.
Sitecore MVC EditFrame implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Sitecore.Mvc.Helpers; | |
using Sitecore.Web.UI.WebControls; | |
using System; | |
using System.IO; | |
using System.Web.UI; | |
public static class SitecoreHelperExtensions | |
{ | |
/// <summary> | |
/// Creates a scoped EditFrame | |
/// </summary> | |
/// <example> | |
/// <code> | |
/// <![CDATA[ | |
/// @using (Html.Sitecore().EditFrame("id", "/sitecore/content/Applications/WebEdit/Edit Frame Buttons/Default")) | |
/// { | |
/// <p>This is rendered inside the frame</p> | |
/// } | |
/// ]]> | |
/// </code> | |
/// </example> | |
/// <param name="htmlHelper">The SitecoreHelper instance</param> | |
/// <param name="id">The ID of the EditFrame</param> | |
/// <param name="buttons">A path to the buttons to use for the EditFrame</param> | |
/// <returns>An IDisposable that will render the end of the frame when disposed</returns> | |
public static MvcEditFrame BeginEditFrame(this SitecoreHelper htmlHelper, string id, string buttons) | |
{ | |
return new MvcEditFrame(new EditFrame | |
{ | |
ID = id, | |
Buttons = buttons | |
}, Sitecore.Mvc.Presentation.PageContext.Current.HtmlHelper.ViewContext.Writer); | |
} | |
} | |
public class MvcEditFrame : IDisposable | |
{ | |
readonly TextWriter textWriter; | |
readonly EditFrame editFrame; | |
bool disposed; | |
public MvcEditFrame(EditFrame editFrame, TextWriter textWriter) | |
{ | |
this.textWriter = textWriter; | |
this.editFrame = editFrame; | |
Render(editFrame.RenderFirstPart); | |
} | |
public void Dispose() | |
{ | |
this.Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (!this.disposed) | |
{ | |
this.disposed = true; | |
Render(editFrame.RenderLastPart); | |
} | |
} | |
private void Render(Action<HtmlTextWriter> renderer) | |
{ | |
using (StringWriter sw = new StringWriter()) | |
using (HtmlTextWriter htmlWriter = new HtmlTextWriter(sw)) | |
{ | |
renderer(htmlWriter); | |
this.textWriter.Write(sw.ToString()); | |
} | |
} | |
public void EndFrame() | |
{ | |
this.Dispose(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment