MVC 2 模板 - 是否可以根据元数据将当前编辑器模板重定向到其显示模板?
对于我正在工作的一个项目,我被要求根据模型提供的元数据将编辑器模板重定向到其显示模板。
现在,我正在寻找一种方法,在它到达编辑器模板之前执行此操作,但这似乎会导致比其价值更多的问题,至少在系统的架构方面是这样。
最简单的例子是字符串编辑器,它是一个简单的文本框,但如果设置了 IsReadOnly,我们希望它仅显示为文本,而不是禁用的文本框。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
if (this.ViewData.ModelMetadata.IsReadOnly)
{
Response.Write(Html.DisplayForModel());
}
else if (this.ViewData.ModelMetadata.ShowForEdit)
{
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" }) %>
<% } %>
到目前为止,我能找到的唯一真正的解决方案是将显示模板复制到编辑器模板中。有谁知道如何在不复制更多代码的情况下做一些可行的事情?
For a project I'm working I've been asked to redirect an editor template to its display template based on metadata that is provided with the model.
Now I was looking at a way to do it before it hits the editor template but that seems to cause more issues than it is worth, at least with how the system has been architected.
The simplest example is the string editor, its a simple textbox but if IsReadOnly is set we want it to only show up as text, not a disabled textbox.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
if (this.ViewData.ModelMetadata.IsReadOnly)
{
Response.Write(Html.DisplayForModel());
}
else if (this.ViewData.ModelMetadata.ShowForEdit)
{
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" }) %>
<% } %>
So far the only real solution I can find is to copy the display template into the editor template. Does anyone have any ideas how I can do something that will work without replicating more code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在编辑器模板本身之外执行此操作?定义一个扩展方法,检查该属性是否为只读,然后显示编辑或显示模板。您需要从 这个答案。
然后在您看来,只需执行
唯一的缺点是这不适用于
Html.EditorForModel()
。Why not do this outside of the editor template itself? Define an extension method that checks if the property is read only then either shows the edit or display template. You'll need to copy the
PropertyHelper
class from this answer.Then in your view just do
Only drawback is this won't work with
Html.EditorForModel()
.