显示不同的字段EditorForModel主场迎战MVC2 DisplayForModel模式 [英] Showing Different fields in EditorForModel vs. DisplayForModel modes in MVC2
问题描述
我有一个 INT STATEID
字段和字符串Statename的
字段,像这样一个视图模型:
I have a viewmodel that has an int StateID
field and a string StateName
field like so:
public class DepartmentViewModel : BaseViewModel, IModelWithId
{
// only show in edit mode
public int StateId { get; set; }
// only show in display mode
public string StateName { get; set; }
}
我有一个只读查看使用 DisplayForModel
和使用更新视图 EditorForModel
。我想在 DisplayForModel
视图显示 Statename的
属性和 EditorForModel
视图中使用 STATEID
属性(我其实呈现在此基础上一个DropDownList)。
I have a read only view that uses DisplayForModel
and an update view that uses EditorForModel
. I want the DisplayForModel
view to show the StateName
property, and the EditorForModel
view use the StateID
property (I am actually rendering a dropdownlist based on this).
我一直无法弄清楚如何装点我的ViewModel属性来创建此行为。
I have not been able to figure out how to decorate my viewmodel properties to create this behavior.
推荐答案
我想一个解决方案,更通用的,所以我创建了一个新的属性:
I wanted a solution that was more generic, so I created a new attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class RenderModeAttribute : Attribute
{
public RenderMode RenderMode { get; set; }
public RenderModeAttribute(RenderMode renderMode)
{
RenderMode = renderMode;
}
}
public enum RenderMode
{
Any,
EditModeOnly,
DisplayModeOnly
}
和包含在我的自定义DataAnnotationsModelMetadataProvider以下code:
And included the following code in my custom DataAnnotationsModelMetadataProvider:
var renderModeAttribute = attributes.OfType<RenderModeAttribute>();
if (renderModeAttribute.Any())
{
var renderMode = renderModeAttribute.First().RenderMode;
switch (renderMode)
{
case RenderMode.DisplayModeOnly:
metadata.ShowForDisplay = true;
metadata.ShowForEdit = false;
break;
case RenderMode.EditModeOnly:
metadata.ShowForDisplay = false;
metadata.ShowForEdit = true;
break;
}
}
所以,我可能只是装点我的模型像这样:
So that I could just decorate my model as so:
public class DepartmentViewModel
{
[RenderMode(RenderMode.EditModeOnly)]
public int StateId { get; set; }
[RenderMode(RenderMode.DisplayModeOnly)]
public string StateName { get; set; }
}
这篇关于显示不同的字段EditorForModel主场迎战MVC2 DisplayForModel模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!