有没有办法动态包装/拦截 HtmlHelper 扩展方法。认为装饰器模式
我希望 System.Web.Mvc.Html 中提供的包装/拦截 HtmlHelper 扩展方法(TextBox、Hidden 等)能够在 2 个单独的用例中重用相同的部分视图。 Partial 的示例:
@model BlogEntry
@Html.TextBoxFor(t => t.Title)
@Html.TextAreaFor(t => t.Body)
@* Etc *@
Partial 的调用者将知道上下文(即是否覆盖或离开 MS imp)。
覆盖的原因多种多样。例如:在 JQuery 模板中使用,在上面的示例中,值属性的输出将为“${Title}”,或者添加 Html5 元数据。
I would like wrap/intercept HtmlHelper extension methods (TextBox, Hidden, etc) provided in System.Web.Mvc.Html to enable reuse of the same Partial Views in 2 separate use cases.
Ex of Partial:
@model BlogEntry
@Html.TextBoxFor(t => t.Title)
@Html.TextAreaFor(t => t.Body)
@* Etc *@
The caller of the Partial will know the context (i.e. whether to override or leave the MS imp).
The reason for overriding are various. For example: to use in JQuery templates, where the output for the value attribute would be "${Title}" on the example above or to add Html5 meta data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您对添加自己的扩展方法有何担忧 - 为什么您必须“创建自己的基本视图页面并完全接管”。您可以在任何页面中调用自定义帮助程序,就像调用内置帮助程序一样:
此外,您可以向方法添加某种标志参数,以控制它是只执行默认功能还是执行自定义功能。
当您创建自己的扩展方法时,您必须更改方法的签名或名称。
我曾经使用唯一的名称,但最终发现我真的希望能够快速区分我自己的实现和默认实现,因此我有时会使用:
基本上,您创建一个新的扩展方法,该方法采用
HtmlHelper;
并返回一个CustomHelpers
。CustomHelpers
类定义了您自己的所有实现:因此,您对
TextBoxFor
的“重写”可以从您的部分视图接收一个标志,以确定它是否返回本机结果或特定于上下文的东西。同样,
CustomHelpers
类是完全可选的。您将添加一个标志参数或类似于自定义助手签名的参数,这样就不会与现有助手发生冲突。它带来的好处是潜在地命名你的助手。你可以有:
I'm not sure what your concerns are with adding your own extension methods -- why you'd have to "create your own base view page and completely take over." You can call your custom helpers in any page just as you would the built-in helpers:
Furthermore, you can add some sort of flag parameter to your method to control whether it just executes the default functionality or something custom.
When you create your own extension methods, you'll have to either change the signature or the name of the method.
I used to use unique names, but ultimately found that I really wanted to be able to quickly discern my own implementations from the default, so I sometimes use:
Basically, you create one new extension method that takes an
HtmlHelper<T>
and returns aCustomHelpers<T>
.The
CustomHelpers<T>
class defines all of your own implementations:So, your "override" of
TextBoxFor
can receive a flag from your partial view to determine whether it returns the native result or something specific to the context.Again, the
CustomHelpers<T>
class is entirely optional. You'll be adding a flag parameter or something similar to the signature of your custom helpers, so you won't collide with existing helpers.The benefit it confers is to potentially namespace your helpers. You could have:
无法拦截对内置帮助器扩展方法的调用。但是,您可以编写自己的扩展方法,根据上下文执行正确的操作。
There is no way to intercept calls to the built-in helper extension methods. However you could write your own extension methods that do the right thing based on the context.