我什至不确定这是否可能,但我想我会检查是否有任何方法可以使这更容易。
首先,我的网站中有一些重复的标记,如下所示:
<div class="module">
<h3>Title</h3>
<div>
<p>Information goes here</p>
</div>
</div>
我想要做的是将它包装在某种帮助/部分中,以便我可以做这样的事情
@MyHelper("This is my Title") {
<p>Here is my custom markup</p>
}
然后,当它渲染时,它会注入(inject)通过
<h3></h3>
之间的参数传入的标题。以及 div 中的自定义标记。自定义标记可以是任何东西,从测试到表单控件,再到局部 View 。这是可能的吗?
最佳答案
还有另外一种方式,不用一次性的把戏,也少了一点工作量,非常适合小 helper 。
@helper MyHelper(string title, Func<object, object> markup) {
<div class="module">
<h3>Title</h3>
<div>
<p>@markup.DynamicInvoke(this.ViewContext)</p>
</div>
</div>
}
这个助手的用法如下所示:
@MyHelper("This is my Title",
@<p>Here is my custom markup</p>
)
或多行:
@MyHelper("This is my Title",
@<text>
<p>More than one line</p>
<p>Of markup</p>
</text>
)
Telerik MVC 控件使用了这个技巧,例如让您在文档加载时添加您的 javascript 代码。
这里还有一个不错的example .还有一些信息here .
关于asp.net-mvc-3 - MVC 3 Razor,具有自定义标记/部分的助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9087792/