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>
Hey Mathias,
We also have a Urls property on the page itself where you can do: this.Urls.UrlFor(new SomeModel()). That will return a string for you that is relative to your app.
That’s excellent! Thanks Josh :) I’ll have a look at that when I get back to the office.
Like a charm. Just needed to add a bit of trimming to get rid of the leading slash.
Updated the article as well, thanks again for the quick feedback.