当我在MVC 4 Web项目中编写下面的代码时
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);
}
}我可以这样用,
@using(Html.BeginTable("abc"))
{
@:<th>content etc</th>
}但我不想用Html开始
举个例子,我想用这个项目,
@using(HtmlExtensions.BeginTable("abc"))
{
@:<th>content etc</th>
}我该如何解决这个问题?谢谢
发布于 2014-08-06 09:07:16
您必须添加HtmlHelper作为参数,因此您必须以某种方式获得对HtmlHelper的引用。例如,如果您在视图中:
@{
var helper = Html
HtmlExtensions.BeginTable(helper,"abc")
}您可以通过调用new HtmlHelper(...)来创建一个新实例,但是必须提供所有参数,如ViewContext等。
https://stackoverflow.com/questions/25156179
复制相似问题