Sitecore glass mapper general link in Mvc 4

by Filip Huysmans   Last Updated June 06, 2017 16:26 PM

Hi i'm currently learning sitecore 7 with MVC4 and glassmapper and I'm having some issues with the general linkfield. I can't seem to ouput the external links (not links to items) correctly from a general linkfield. What am I doing wrong?

My model:

[SitecoreType(TemplateId = "{F8168BAF-6916-47FE-BC7F-DE3B033CE233}")]
public class SocialLink : AbstractBase
{

    [SitecoreField]
    public virtual string Description { get; set; }

    [SitecoreField]
    public virtual string Class { get; set; }

    [SitecoreField(FieldType = SitecoreFieldType.GeneralLink)]
    public virtual Link Url { get; set; }

}

in the view:

@foreach (var socialLink in Model.SocialFolder.Socials)
{
     <a href="@socialLink.Url" class="connect @socialLink.Class">@socialLink.Description</a>                
}

Output:

<a href="Glass.Mapper.Sc.Fields.Link" class="connect slideshare">Read us on Slideshare</a>

Thanks in advance.



Answers 2


Is the model auto-generated or did you create them manually? What type is Link, Glass.Mapper.Sc.Fields.Link? If so you need @socialLink.Url.Url, you want the Url property from the Link field called Url.

@foreach (var socialLink in Model.SocialFolder.Socials)
{
     <a href="@socialLink.Url.Url" class="connect @socialLink.Class">@socialLink.Description</a>                
}

I would be very tempted to rename Class and Url properties to something else, possibly CssClass and SocialMediaUrl or something so as not to cause confusion.

jammykam
jammykam
January 06, 2014 15:27 PM

So that Anchors and Querystrings are supported, it's best to use link.BuildUrl((SafeDictionary<string>)null)

There are two Link.BuildUrl()methods and, annoyingly, they both have default parameters (although one marked as obsolete). You will need to specify which one via a typed null, or...

You can add an extension method which will make things easier

public static class GlassFieldExtensions
{
    public static string GetUrl(this Link link)
    {
        return link.BuildUrl(null as SafeDictionary<string>);
    }
}

And in the HTML:

@foreach (var socialLink in Model.SocialFolder.Socials)
{
     <a href="@socialLink.GetUrl()" class="connect @socialLink.Class">@socialLink.Description</a>                
}
Dann
Dann
June 06, 2017 16:25 PM

Related Questions


Sitecore 8.2 -- Glassmapper throwing error

Updated February 01, 2018 15:26 PM

Writing unit test cases for Sitecore project

Updated October 06, 2017 05:26 AM