Glass Mapper RenderLink链接描述-默认文本(如果为空) [英] Glass Mapper RenderLink link description - default text if empty

查看:85
本文介绍了Glass Mapper RenderLink链接描述-默认文本(如果为空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当内容编辑器设置了链接但实际上未放入链接描述时,我需要一种方法来捕获它.此刻,它只是呈现空格.上面的作品,但它笨拙,我需要使用RenderLink将它放在任何地方.如果文本为空,该如何默认?

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?

推荐答案

我已经创建了一个扩展方法来解决该问题.
请注意,我扩展了GlassHtml而不是GlassView,因为您可能希望传递与用于视图的模型类型不同的模型类型.

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"))

仍然有点笨拙,因为您需要将IGlassHtml强制转换为GlassHtml,但是它可以工作.
如果您始终为视图定义了正确的模型(因此不需要指定 model 参数),则可以将此扩展方法放在GlassView上.

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.

这篇关于Glass Mapper RenderLink链接描述-默认文本(如果为空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆