Luc*_* CB 4 .net asp.net asp.net-mvc html-helper
我怎么能创建这样的东西:Html.MyApp.ActionLink()?谢谢.
你不能这样做.您可以添加到Html类的唯一方法是通过扩展方法.您无法添加"扩展属性",这是您需要使用的Html.MyApp.你最接近的是Html.MyApp().Method(...)
你最好的选择可能是将它们作为Html的扩展方法包含在内,或者完全创建一个新的类(例如.MyAppHtml.Method(...)或MyApp.Html.Method(...)).最近有一篇博客文章专门展示了这些方法的"Html5"课程,但不幸的是我的谷歌技能让我失望了,我找不到它:(
要执行类似于Html.MyApp().ActionLink()您需要创建扩展方法的操作HtmlHelper,它将使用您的自定义方法返回类的实例:
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)));
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您需要导入此类所在的命名空间Web.config,如下所示:
<?xml version="1.0"?>
<configuration>
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="MyHelper"/>
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2565 次 |
| 最近记录: |