5

我正在阅读 ASP.NET MVC 及其所有有趣的用途,我刚刚发现了DataTemplates

在我急于测试这个东西的过程中,我将我的一个更简单的模型转换为使用它@Html.DisplayForModel()@Html.EditForModel()它就像一个幸运符:)

我立即发现的一件事是,我无法轻松定义一个字段以显示在显示视图上,但根本不存在以进行编辑......

4

3 回答 3

12

您可以使用 IMetadataAware 接口创建属性,该属性将在元数据中设置 ShowForEdit 和 ShowForDislay:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TemplatesVisibilityAttribute : Attribute, IMetadataAware
{
    public bool ShowForDisplay { get; set; }

    public bool ShowForEdit { get; set; }

    public TemplatesVisibilityAttribut()
    {
        this.ShowForDisplay = true;
        this.ShowForEdit = true;
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        if (metadata == null)
        {
            throw new ArgumentNullException("metadata");
        }

        metadata.ShowForDisplay = this.ShowForDisplay;
        metadata.ShowForEdit = this.ShowForEdit;
    }

}

然后你可以像这样将它附加到你的财产上:

public class TemplateViewModel
{
  [TemplatesVisibility(ShowForEdit = false)]
  public string ShowForDisplayProperty { get; set; }

  public string ShowAlwaysProperty { get; set; }
}

这就是你所需要的。

于 2011-04-07T15:44:29.503 回答
2

您可以编写自定义元数据提供程序并设置ShowForEdit元数据属性。所以从一个自定义属性开始:

public class ShowForEditAttribute : Attribute
{
    public ShowForEditAttribute(bool show)
    {
        Show = show;
    }

    public bool Show { get; private set; }
}

然后是自定义模型元数据提供者:

public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(
        IEnumerable<Attribute> attributes,
        Type containerType, 
        Func<object> modelAccessor, 
        Type modelType, 
        string propertyName
    )
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
        var sfea = attributes.OfType<ShowForEditAttribute>().FirstOrDefault();
        if (sfea != null)
        {
            metadata.ShowForEdit = sfea.Show;
        }
        return metadata;
    }
}

然后在以下位置注册此提供程序Application_Start

ModelMetadataProviders.Current = new MyModelMetadataProvider();

最后装饰:

public class MyViewModel
{
    [ShowForEdit(false)]
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

现在,如果您认为您有:

@model MyViewModel

<h2>Editor</h2>
@Html.EditorForModel()

<h2>Display</h2>
@Html.DisplayForModel()

Prop1属性不会包含在编辑器模板中。

备注:您可以对ShowForDisplay元数据属性执行相同的操作。

于 2011-04-07T15:24:51.733 回答
0

您可以使用 Html.DisplayTextbox 或其他选项之一显示您想要的每个字段吗?这样,您还可以自定义引用该字段的外观和标签。

于 2011-04-07T15:25:35.580 回答