asp.net mvc 3 -如何排除一个字段从@Html.EditForModel(),但有它显示使用Html.Dis



我正在阅读ASP。. NET MVC和它的所有有趣的用途,我刚刚发现关于DataTemplates。

在我急于测试这个东西的时候,我把我的一个更简单的模型转换为使用@Html.DisplayForModel()@Html.EditForModel(),它像一个幸运符一样工作:)

我立即发现的一件事是,我不能很容易地定义一个字段,显示在显示视图中,但不存在的编辑…

您可以使用IMetadataAware接口的create属性来设置元数据中的ShowForEdit和showfordisplay:

[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; }
}

您可以编写自定义元数据提供程序并设置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元数据属性做同样的事情。

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

最新更新