Skip to content

Instantly share code, notes, and snippets.

Created January 27, 2016 17:31
Show Gist options
  • Select an option

  • Save anonymous/396e130de4f65e1e2a2a to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/396e130de4f65e1e2a2a to your computer and use it in GitHub Desktop.
HtmlHelper extension to toggle between span & anchor easily
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, IDictionary<string, object> htmlAttributes)
{
var tag = useAnchor ? "a" : "span";
var tagBuilder = new TagBuilder(tag);
tagBuilder.MergeAttributes(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