1

对于我正在工作的项目,我被要求根据模型提供的元数据将编辑器模板重定向到其显示模板。

现在,我正在寻找一种在它到达编辑器模板之前执行此操作的方法,但这似乎会导致比其价值更多的问题,至少与系统的架构方式有关。

最简单的例子是字符串编辑器,它是一个简单的文本框,但如果设置了 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" }) %>
<% } %>

到目前为止,我能找到的唯一真正的解决方案是将显示模板复制到编辑器模板中。有没有人知道如何在不复制更多代码的情况下做一些可以工作的事情?

4

1 回答 1

1

为什么不在编辑器模板本身之外执行此操作?定义一个扩展方法,检查属性是否为只读,然后显示编辑或显示模板。您需要从这个答案PropertyHelper中复制课程。

public MvcHtmlString DisplayOrEditFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> selector)
{
    var property = PropertyHelper<TModel>.GetProperty(selector);
    if(property.CanWrite)
    {
        return helper.EditorFor(selector);
    }
    return helper.DisplayFor(selector);
}

然后在你看来只是做

<%: Html.DisplayOrEditFor(x => x.Name) %>

唯一的缺点是这不适用于Html.EditorForModel().

于 2010-07-24T03:47:51.350 回答