Reputation: 2688
Dynamically resolving component links in views using DD4T - not within rich text fields using ResolveRichText()
- but if component A has a component link field with a link to component B and within your view you want to render a url to the page component B is published on ...
There's no helper for this in the solution - is that right?
Bit rusty with ASP.NET MVC 3, so purists look away, but the following works, I just need to create the Html Helper.
@using DD4T.Providers.SDLTridion2011sp1;
@{
var linkFactory = new LinkFactory();
linkFactory.LinkProvider = new TridionLinkProvider();
var link = linkFactory.ResolveLink(Model.Component.Fields["related_link"].LinkedComponentValues[0].Id);
}
Just though it was a bit strange there's no helper already in the project for this.
Cheers
Upvotes: 3
Views: 1163
Reputation: 4835
The nice part of adding your own extension method is that you have the ability to do something additionally in there.
We for instance use it to differentiate between component.Multimedia.Url and LinkFactory.ResolveLink(component.Id) depending on weather the component is a multimedia component or a regular one (since multimedia components like a PDF file are normally not placed on a page so dynamic link resolving won't return a result for you.
Upvotes: 2
Reputation: 3548
I think you are right, this should be in the framework. But fortunately, it is very easy to add this. Just create a helper class with an extension method like this:
namespace MyApp.Helpers
{
public static class ModelHelper
{
public static string GetResolvedUrl(this IComponent component)
{
return GetResolvedUrl(component, null, null);
}
}
}
Now, if you make sure your view is using the namespace MyApp.Helpers, you can do this in your component views:
@model DD4T.ContentModel.Component
@using MyApp.Helpers
<a href="@Model.GetResolvedUrl()">click here</a>
We are likely to include this in the framework soon.
Upvotes: 9
Reputation: 1125
There is indeed no HTML helper for resolving a link. Main reason is probably that (according to the MVC principles) the link should already be resolved in the Model your view is rendering.
If you checkout the ContentModel class from the dd4t.ContentModel project, there is a (commented out) property 'ResolvedUrl' for a component. This is never implemented, but it is a more approperiate place for resolving the link. But your code does the job, so feel free to implement your own HTML helper.
Upvotes: 6