David
David

Reputation: 1

How to display enums in ASP.NET MVC

I am new in MVC and Entity framework, so I have some problem in my first project. So sorry if my question is to noob :(

What I have at this point:
I have table users(ID, Name, Password, TypeID, StatusID) and I have lookup table for this fields TypeID, StatusID UserTypes and UserStatuses.

Here is some code for more clarity

CREATE TABLE [dbo].[Users](
    [ID] [int] NOT NULL,
    [Name] [varchar](512) NOT NULL,
    [Password] [varchar](128) NOT NULL,
    [TypeID] [int] NULL,
    [StatusID] [int] NULL
)

CREATE TABLE [dbo].[UserStatuses](
    [ID] [int] NOT NULL,
    [Description] [nvarchar](128) NULL
)


CREATE TABLE [dbo].[UserTypes](
    [ID] [int] NOT NULL,
    [Description] [nvarchar](128) NULL
)

In UserStatuses Table I store "active", "Blocked" and in UserTypes "Admin", "User", "guest"

Values in UserTypes mey change in future so, I don't wont to convert Users.TypeID field in Enum.(this is important for me !)

What I need:
How display user friendly values "active", "Blocked" for StatusID and "Admin", "User", "guest" for TypeID field, instead of number editor when I am generating view ?

link to some good article is welcome Smile :)

Upvotes: 0

Views: 233

Answers (2)

SBirthare
SBirthare

Reputation: 5137

EntityFramework allows you to declare what it call it as "Navigational Property" in your POCO entity class. For more information read here.

So in you case what you can do is to declare one navigation property in your Users POCO entity class representing UserStatuses and UserTypes as shown below:

    public class User
    {
        public int id { get; set; }

        // Other properties representing table columns here

        public UserStatus UserStatus { get; set; }
        public UserType UserType { get; set; }
    }

   public class UserStatus
   {
        public int Id { get; set; }
        public string Description  { get; set; }
   }

Now you can refer UserStatus object corresponding to one User. i.e. in UI you can use user.UserStatus.Description to display the value.

Upvotes: 1

natemcmaster
natemcmaster

Reputation: 26823

There are dozens of articles on http://asp.net/ that can guide you through using these frameworks.

In particular, you may want to read Introduction to ASP.NET Web Programming Using the Razor Syntax (C#) which may help you understand better how to display your data in your view.

Upvotes: 1

Related Questions