创建像 Helper.BeginForm() 这样的 MVC3 Razor Helper
我想创建一个助手,我可以像 Helper.BeginForm() 一样在括号之间添加内容。我不介意为我的助手创建一个开始、结束,但这样做非常简单且容易。
基本上我想做的就是将内容包装在这些标签之间,以便它们呈现已经格式化的
参数,
@using Html.Section("full", "The Title")
{
This is the content for this section
<p>More content</p>
@Html.TextFor("text","label")
etc etc etc
}
“full”是该 div 的 css id,“the title”是该部分的标题。
除了做我想做的事情之外,还有更好的方法来实现这一目标吗?
预先感谢您的任何帮助。
I want to create a helper that i can add content between the brackets just like Helper.BeginForm() does. I wouldnt mind create a Begin, End for my helper but it's pretty simple and easy to do it that way.
basically what i am trying to do is wrapping content between these tags so they are rendered already formatted
something like
@using Html.Section("full", "The Title")
{
This is the content for this section
<p>More content</p>
@Html.TextFor("text","label")
etc etc etc
}
the parameters "full" is the css id for that div and "the title" is the title of the section.
Is there a better way to achieve this other than doing what i am trying to do?
thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是完全有可能的。在 MVC 中使用
Helper.BeginForm
之类的方法完成此操作的方式是,该函数必须返回一个实现IDisposable
的对象。IDisposable
接口 定义了一个名为的方法Dispose
在对象被垃圾收集之前调用。在 C# 中,
using
关键字有助于限制对象的范围,并在对象离开范围时对其进行垃圾收集。因此,将它与 IDisposable 一起使用是很自然的。您需要实现一个实现
IDisposable
的Section
类。它必须在构造时呈现您的部分的开放标记,并在处置时呈现关闭标记。例如:现在类型可用,您可以扩展 HtmlHelper。
It's totally possible. The way this is done in MVC with things like
Helper.BeginForm
is that the function must return an object that implementsIDisposable
.The
IDisposable
interface defines a single method calledDispose
which is called just before the object is garbage-collected.In C#, the
using
keyword is helpful to restrict the scope of an object, and to garbage-collect it as soon as it leaves scope. So, using it withIDisposable
is natural.You'll want to implement a
Section
class which implementsIDisposable
. It will have to render the open tag for your section when it is constructed, and render the close tag when it is disposed. For example:Now that the type is available, you can extend the HtmlHelper.
这是我为此编写的一个小实用程序。它更通用一些,因此您可以将它用于任何标签和任何属性。它被设置为 HtmlHelper 上的扩展方法,因此您可以直接在 Razor 内以及在代码内使用它。
Here is a little util I wrote to do this. It is a little more generic so you can use it for any tag and with any attributes. It is setup as an extension method on HtmlHelper so you can use it right from within Razor as well as from within code.