fubumvc

FubuMVC: How do I add a new method a la DisplayFor


I want to do something like the following in my spark view.

@{this.LinkTo("1234")}

Which should output something like

<a href="domain.tld?var=1234">1234</a>

I cannot seem to find a good way to do this.

Most searches for "fubumvc htmlhelpers" end up giving me more pages about htmlhelpers in msmvc.

A plus would be if I could put the code in a separate assembly that I can share between multiple sites.

Solution

namespace MyNamespace
{
    public static class FubuPageExtensions
    {
        public static HtmlTag LinkTo(this IFubuPage page, string input)
        {
            return new LinkTag(input, "domain.tld?var={0}".ToFormat(input));
        }
    }
}

...and in my spark view

<use namespace="MyNamespace" />

${this.LinkTo(Model.Something)}

Solution

  • I had a similar requirement and I solved it this way (not sure if this is the best approach, but it worked for my scenario).

    The idea is to create an extension method on the IFubuPage interface, which returns a new HtmlTag object. Please note that I'm using the Razor view engine, not entirely sure if this would work for Spark as well.

    So for example, the following code would produce a new <abbr /> tag:

    public static HtmlTag TimeAgoFor(this IFubuPage page, DateTime input)
    {
        return new HtmlTag("abbr")
            .Title(input.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK"))
            .AddClass("timeago")
            .Text(input.ToString("dd-MM-yyyy HH:mm"));
        }
    }
    

    In your scenario, I think this should suffice then:

    public static HtmlTag LinkTo(this IFubuPage page, string input)
    {
         return new LinkTag(input, "domain.tld?var={0}".ToFormat(input));
    }