MVC HTML辅助自定义命名空间 [英] MVC HTML Helper custom namespace

查看:127
本文介绍了MVC HTML辅助自定义命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以创造这样的事情:Html.MyApp.ActionLink()? 谢谢你。

how I can create something like this: Html.MyApp.ActionLink()? Thanks.

推荐答案

您无法做到这一点。你可以添加到HTML类的唯一方法是通过一个扩展方法。不能添加扩展属性,这是将需要为你使用 Html.MyApp 。你能来最接近的是 Html.MyApp()方法(...)

You can't do this. The only way you can add to the Html class is via an extension method. You cannot add "Extension Properties", which is what would be required for you to use Html.MyApp. The closest you could come is Html.MyApp().Method(...)

您最好的选择可能是为包括他们作为HTML扩展方法,或完全(如 MyAppHtml.Method(...)或创建一个新类 MyApp.Html.Method(...))。有一个博客帖子最近围绕具体表示是Html5的类的这些方法,但不幸的是我的谷歌技能都没有了我,我不能找到它:(

Your best bet is probably to either include them as extension methods on Html, or create a new class completely (eg. MyAppHtml.Method(...) or MyApp.Html.Method(...)). There was a blog post around recently specifically showing an "Html5" class with these methods, but unfortunately my Google skills are failing me, and I can't find it :(

要像做 Html.MyApp()。ActionLink的()你需要创建一个扩展方法的HtmlHelper ,返回一个类的实例与您的自定义的方法:

To do something like Html.MyApp().ActionLink() you need to create an extension method on HtmlHelper, that returns an instance of a class with your custom method:

namespace MyHelper
{
    public static class MyHelperStuff
    {
        // Extension method - adds a MyApp() method to HtmlHelper
        public static MyHelpers MyApp(this HtmlHelper helper)
        {
            return new MyHelpers();
        }
    }

    public class MyHelpers
    {
        public IHtmlString ActionLink(string blah)
        {
            // Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
            return new MvcHtmlString(string.Format("<a href=\"#\">{0}</a>", HttpUtility.HtmlEncode(blah)));
        }
    }
}

注意:您需要导入这个类是在的Web.config ,这样的命名空间:

Note: You'll need to import the namespace this class is in in Web.config, like this:

<?xml version="1.0"?>
<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="MyHelper"/>
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

这篇关于MVC HTML辅助自定义命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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