How to get URL to FuBuMVC input model endpoint in a view

I wrote a small extension method for retrieving the URL to an input model endpoint in FuBuMVC together with my collegue Christer Bermar today. What we wanted to achieve was to have the relative address without the leading slash added to a custom attribute placed on a span tag.

Note: If you don’t enjoy reinventing wheels, please have a look at Josh’s comment below and use the built-in @this.Urls.UrlFor(new SomeModel()) instead.

<span custom-attribute="relative/url/to/fubumvc/endpoint">Some content</span>

Obviously, we could not make use of the built-in @this.LinkTo(..) method, since it would return the entire a-tag and not just the web address. Not being able to find an alternative, resulted in the following piece of code.

FubuPageExtensions.cs

public static class FubuPageExtensions
{
 public static string UrlFor(this IFubuPage page, object inputModel, bool removeLeadingSlash = false)
 {
  if(inputModel == null)
  {
    return string.Empty;
  }
  var url = page
        .AuthorizedLinkTo(alt => alt.EndpointFor(inputModel))
        .Attr("href");
  return removeLeadingSlash ? url.TrimStart('/') : url;
 }
}

The extension method is rather simple, all it does is fetching the endpoint link from the Fubupage extracting it’s href attribute. To use it, simply call it with your input model from the view as below.

<span custom-attribute="@this.UrlFor(new SomeModel(), true)">Some content</span>
@* yields *@
<span custom-attribute="relative/url/to/fubumvc/endpoint">Some content</span>

3 Comments

  1. Josh Arnold September 19, 2012
    • Mathias Kunto September 19, 2012
    • Mathias Kunto September 20, 2012