C# 为自己的助手创建?比如Html.begin
我想知道,是否有可能创建您自己的助手定义,并使用?例如,创建表单的以下内容:C# 为自己的助手创建?比如Html.begin,c#,.net,asp.net-mvc-3,razor,html-helper,C#,.net,Asp.net Mvc 3,Razor,Html Helper,我想知道,是否有可能创建您自己的助手定义,并使用?例如,创建表单的以下内容: using (Html.BeginForm(params)) { } 我想自己做一个这样的帮手。我想举一个简单的例子 using(Tablehelper.Begintable(id) { <th>content etc<th> } 使用(Tablehelper.Begintable(id) { 内容等 } 在我看来,这将输出 <table> <th>c
using (Html.BeginForm(params))
{
}
我想自己做一个这样的帮手。我想举一个简单的例子
using(Tablehelper.Begintable(id)
{
<th>content etc<th>
}
使用(Tablehelper.Begintable(id)
{
内容等
}
在我看来,这将输出
<table>
<th>content etc<th>
</table>
内容等
这可能吗?如果可能,怎么可能
谢谢当然,有可能:
public static class HtmlExtensions
{
private class Table : IDisposable
{
private readonly TextWriter _writer;
public Table(TextWriter writer)
{
_writer = writer;
}
public void Dispose()
{
_writer.Write("</table>");
}
}
public static IDisposable BeginTable(this HtmlHelper html, string id)
{
var writer = html.ViewContext.Writer;
writer.Write(string.Format("<table id=\"{0}\">", id));
return new Table(writer);
}
}
public静态类
{
私有类表:IDisposable
{
专用只读文本编写器;
公共表(TextWriter)
{
_作家=作家;
}
公共空间处置()
{
_作者:写(“”);
}
}
公共静态IDisposable起始表(此HtmlHelper html,字符串id)
{
var writer=html.ViewContext.writer;
Write.Write(string.Format(“,id));
返回新表(writer);
}
}
然后:
@using(Html.BeginTable("abc"))
{
@:<th>content etc<th>
}
@使用(Html.BeginTable(“abc”))
{
@:内容等
}
将产生:
<table id="abc">
<th>content etc<th>
</table>
内容等
我还建议您阅读。是的;但是,要使用
Tablehelper.
您需要对基本视图进行子类化,并添加Tablehelper
属性。不过,可能更简单的方法是向HtmlHelper
添加扩展方法:
public static SomeType BeginTable(this HtmlHelper html, string id) {
...
}
这将允许您编写:
using (Html.BeginTable(id))
{
...
}
但这反过来又需要各种其他的管道(从
BeginTable
开始元素,并在返回值上以Dispose()
结束元素)。好的,谢谢。因为您是在类中完成的,所以我认为使用常规的@helper方法()是不可能的?还有,我应该把它放在哪里?我试着把它和其他助手一起放在我的app_code文件夹中,但这似乎不起作用。@RonSijm,你可以把这个类放在HtmlExtensions.cs
文件中,比如Extensions
文件夹中。只要确保你把这个类定义的名称空间放在要在视图中作用域以便可以访问扩展方法:@using-AppName.Extensions
。谢谢,这似乎很有效。但太糟糕了,仅将using放在_layout.cshtml中不起作用。@RonSijm,您可以将名称空间添加到~/Views/web.config
文件的
部分(不是~/web.config
)。这样,帮助程序将在您的应用程序中普遍可用。或者只需将其命名空间更改为System.web.Mvc.Html
,这是定义所有标准帮助程序的地方。需要注意的一点是……您应该覆盖ToString()在Table类中返回empty…如果不是,您将看到类似于YourDomain.HtmlExtensions.Table的文本a long以及该表。