简体   繁体   English

FubuMVC:如何在DisplayFor中添加新方法

[英]FubuMVC: How do I add a new method a la DisplayFor

I want to do something like the following in my spark view. 我想在火花视图中执行以下操作。

@{this.LinkTo("1234")}

Which should output something like 哪个应该输出类似

<a href="domain.tld?var=1234">1234</a>

I cannot seem to find a good way to do this. 我似乎找不到解决此问题的好方法。

Most searches for "fubumvc htmlhelpers" end up giving me more pages about htmlhelpers in msmvc. 大多数搜索“ fubumvc htmlhelpers”最终都给了我更多有关msmvc中htmlhelpers的页面。

A plus would be if I could put the code in a separate assembly that I can share between multiple sites. 如果我可以将代码放在可以在多个站点之间共享的单独程序集中,则将是一个加分。

Solution

namespace MyNamespace
{
    public static class FubuPageExtensions
    {
        public static HtmlTag LinkTo(this IFubuPage page, string input)
        {
            return new LinkTag(input, "domain.tld?var={0}".ToFormat(input));
        }
    }
}

...and in my spark view ...在我的视野中

<use namespace="MyNamespace" />

${this.LinkTo(Model.Something)}

I had a similar requirement and I solved it this way (not sure if this is the best approach, but it worked for my scenario). 我有一个类似的要求,我用这种方式解决了(不确定这是否是最好的方法,但是它适用于我的情况)。

The idea is to create an extension method on the IFubuPage interface, which returns a new HtmlTag object. 这个想法是在IFubuPage接口上创建一个扩展方法,该方法返回一个新的HtmlTag对象。 Please note that I'm using the Razor view engine, not entirely sure if this would work for Spark as well. 请注意,我正在使用Razor视图引擎,不能完全确定这是否也适用于Spark。

So for example, the following code would produce a new <abbr /> tag: 因此,例如,以下代码将产生一个新的<abbr />标签:

public static HtmlTag TimeAgoFor(this IFubuPage page, DateTime input)
{
    return new HtmlTag("abbr")
        .Title(input.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK"))
        .AddClass("timeago")
        .Text(input.ToString("dd-MM-yyyy HH:mm"));
    }
}

In your scenario, I think this should suffice then: 在您的情况下,我认为这样就足够了:

public static HtmlTag LinkTo(this IFubuPage page, string input)
{
     return new LinkTag(input, "domain.tld?var={0}".ToFormat(input));
}

Make sure you have your "FubuPageExtensions" namespace in your spark file. 确保您的spark文件中具有“ FubuPageExtensions”命名空间。

As noted in the comments, use a "_global.spark" file in the Shared directory so all .spark files have the extensions namespace. 如注释中所述,请在Shared目录中使用“ _global.spark”文件,以便所有.spark文件都具有扩展名命名空间。

I don't know if this would appeal to you but you can also declare your helpers in one of the default namespaces that the fubu.spark viewengine supports, eg: 我不知道这是否会吸引您,但是您也可以在fubu.spark视图引擎支持的默认名称空间之一中声明您的助手,例如:

namespace FubuMVC.Core.UI
{
public static class MyHelper{
public static HtmlTag LinkTo(this IFubuPage page, string input)
{
     return new LinkTag(input, "domain.tld?var={0}".ToFormat(input));
}
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM