PeterG
PeterG

Reputation: 344

Glass Mapper RenderLink link description - default text if empty

<li>@if (string.IsNullOrWhiteSpace(topLinks.Target.Text))
    {
      topLinks.Target.Text = "EMPTY DESCRIPTION";
    }
    @(RenderLink(topLinks, x => x.Target, isEditable: true))
</li>

I need a way to catch it when a Content Editor has set up a link, but not actually put a Link Description in. At the moment it just renders spaces. The above works, but it's clunky and I need to put it everywhere I use a RenderLink. How do I default the text if it's empty?

Upvotes: 0

Views: 2072

Answers (1)

Ruud van Falier
Ruud van Falier

Reputation: 8877

I've created an extension method to work around it.
Note that I've extended GlassHtml and not GlassView because you may want to pass a different model type than the one that's used for the view.

namespace ParTech.MvcDemo.Context.Extensions
{
    using System;
    using System.Linq.Expressions;
    using System.Web;
    using Glass.Mapper.Sc;
    using Glass.Mapper.Sc.Fields;

    public static class GlassHtmlExtensions
    {
        public static HtmlString RenderLinkWithDefaultText<T>(this GlassHtml glassHtml, T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = true, string defaultText = null)
        {
            var linkField = field.Compile().Invoke(model) as Link;

            if (linkField == null || string.IsNullOrEmpty(linkField.Text))
            {
                return new HtmlString(glassHtml.RenderLink(model, field, attributes, isEditable, defaultText));
            }

            return new HtmlString(glassHtml.RenderLink(model, field, attributes, isEditable));
        }
    }
}

You can now do this in your view:

@(((GlassHtml)this.GlassHtml).RenderLinkWithDefaultText(MyModel, x => x.LinkField, null, true, "Static default text"))

Still a bit hacky because you need to cast the IGlassHtml to GlassHtml, but it works.
If you always have the correct model defined for you view (and thus don't need to specify the model parameter) you could put this extension method on GlassView.

Upvotes: 4

Related Questions