-
-
Save davemcdermid/aceb6d20611c87073405 to your computer and use it in GitHub Desktop.
HtmlHelper extension to toggle between span & anchor easily
This file contains hidden or 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 System; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Web.Mvc; | |
| public static class SpanchorExtension | |
| { | |
| public static Spanchor Spanchor(this HtmlHelper htmlHelper, bool useAnchor, string url, object htmlAttributes = null) | |
| { | |
| var tag = useAnchor ? "a" : "span"; | |
| var tagBuilder = new TagBuilder(tag); | |
| tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); | |
| if (useAnchor) | |
| { | |
| tagBuilder.MergeAttribute("href", url); | |
| } | |
| htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); | |
| return new Spanchor(htmlHelper.ViewContext, tagBuilder); | |
| } | |
| } | |
| public class Spanchor : IDisposable | |
| { | |
| private bool _disposed; | |
| private readonly TagBuilder _tagBuilder; | |
| private readonly TextWriter _writer; | |
| public Spanchor(ViewContext viewContext, TagBuilder tagBuilder) | |
| { | |
| if (viewContext == null) | |
| { | |
| throw new ArgumentNullException("viewContext"); | |
| } | |
| if (tagBuilder == null) | |
| { | |
| throw new ArgumentNullException("tagBuilder"); | |
| } | |
| _tagBuilder = tagBuilder; | |
| _writer = viewContext.Writer; | |
| } | |
| public void Dispose() | |
| { | |
| Dispose(true /* disposing */); | |
| GC.SuppressFinalize(this); | |
| } | |
| protected virtual void Dispose(bool disposing) | |
| { | |
| if (_disposed) | |
| { | |
| return; | |
| } | |
| _disposed = true; | |
| _writer.Write(_tagBuilder.ToString(TagRenderMode.EndTag)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment