Last active
August 29, 2015 14:25
-
-
Save corycook/58b2f841e970d6194835 to your computer and use it in GitHub Desktop.
C# Web MVC BeginActionLink
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.Collections.Generic; | |
| using System.Web.Mvc; | |
| namespace TestWeb.Extensions | |
| { | |
| public static class HtmlHelperExtensions | |
| { | |
| static Dictionary<string, object> ToDictionary(object o) | |
| { | |
| return o.GetType().GetProperties().ToDictionary(n => n.Name, n => n.GetValue(o, null)); | |
| } | |
| public static MvcLink BeginActionLink(this HtmlHelper helper, string actionName, string controllerName, object routeValues, object htmlAttributes) | |
| { | |
| var uh = new UrlHelper(helper.ViewContext.RequestContext); | |
| var attr = ToDictionary(htmlAttributes); | |
| attr.Add("href", uh.Action(actionName, controllerName, routeValues)); | |
| return new MvcLink(helper.ViewContext.Writer, attr); | |
| } | |
| } | |
| } |
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; | |
| namespace TestWeb.Extensions | |
| { | |
| public class MvcLink : IDisposable | |
| { | |
| readonly TextWriter _writer; | |
| readonly TagBuilder builder = new TagBuilder("a"); | |
| public MvcLink(TextWriter writer, IDictionary<string, object> htmlAttributes) | |
| { | |
| _writer = writer; | |
| builder.MergeAttributes(htmlAttributes); | |
| _writer.WriteLine(builder.ToString(TagRenderMode.StartTag)); | |
| } | |
| public void Dispose() | |
| { | |
| _writer.WriteLine(builder.ToString(TagRenderMode.EndTag)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment