Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

asp.net mvc - Showing Different fields in EditorForModel vs. DisplayForModel modes in MVC2

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

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).

I have not been able to figure out how to decorate my viewmodel properties to create this behavior.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A comment on CodeGrue's answer.

Make the attribute inherit IMetadataAware instead. That way you don't need to build your own DataAnnotationsModelMetadataProvider.

The new attribute would become something like:

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

    public RenderModeAttribute(RenderMode renderMode)
    {
        RenderMode = renderMode;
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        switch (RenderMode)
        {
            case RenderMode.DisplayModeOnly:
                metadata.ShowForDisplay = true;
                metadata.ShowForEdit = false;
                break;

            case RenderMode.EditModeOnly:
                metadata.ShowForDisplay = false;
                metadata.ShowForEdit = true;
                break;

            case RenderMode.None:
                metadata.ShowForDisplay = false;
                metadata.ShowForEdit = false;
                break;
        }
    }
}

public enum RenderMode
{
    Any,
    EditModeOnly,
    DisplayModeOnly
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...