如何从@ Html.EditForModel排除字段(),但有它显示了使用Html.DisplayForModel() [英] How to exclude a field from @Html.EditForModel() but have it show using Html.DisplayForModel()
问题描述
我在ASP.NET MVC阅读和它的所有有趣的用途,我只是发现了有关的的DataTemplates 。
I am reading up on ASP.NET MVC and all of it's fun uses and I just found out about DataTemplates.
在我急着要测试这个东西的时候,我将我的简单的车型之一到使用 @ Html.DisplayForModel()
和 @Html .EditForModel()
和它的工作就像一个幸运符,它是:)
In my hurry to test this thing out, I converted one of my simpler models over to using @Html.DisplayForModel()
and @Html.EditForModel()
and it worked like a lucky charm that it is :)
一件事,我立即发现,虽然是我不能轻易定义一个字段,以显示在显示屏的意见,但不会是present在所有的编辑...
One thing that I immediately found out though was that I could not easily define a field to show up on display views but not be present at all for editing...
推荐答案
您可以使用IMetadataAware界面的创建属性,它会设置ShowForEdit和ShowForDislay在元数据:
You can make use of IMetadataAware interface an create attribute which will set ShowForEdit and ShowForDislay in Metadata:
[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;
}
}
然后你可以将其连接到你的财产是这样的:
Then you can attach it to your property like this:
public class TemplateViewModel
{
[TemplatesVisibility(ShowForEdit = false)]
public string ShowForDisplayProperty { get; set; }
public string ShowAlwaysProperty { get; set; }
}
这是你所需要的。
And this is all you need.
这篇关于如何从@ Html.EditForModel排除字段(),但有它显示了使用Html.DisplayForModel()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!