I was working on an MVC project today at work, and I came by a problem, which I couldn't really figure out the best practice for.
Consider that I have a User, and each user have a UserType-ID or Code (not necessarily residing in another table). In this case the UserType is not in another table, but is hardcoded. But in the future, should be loaded from a persistence layer.
ID 1 is an Admin
ID 2 is a Moderator
ID 3 is a normal user.
Now I have a plain Index, Create, Edit view of this User, and the UserType Id is a Dropdownlist of UserTypes.
So far, the code built the SelectList in the Controller, and there it was all hardcoded.
On the index page, I would want to display the user type "name", rather than the id that represented that.
So I ended up, keeping the hard coded value in the Controller, and in the UserViewModel, I added a "UserTypeStr" property, that would give me a name for that user type.
Like this:
public class User
{
public int UserType{get;set;}
// other fields...
public string UserTypeStr
{
get
{
switch(UserType)
{
case 1: return "Admin";
case 2: return "Moderator";
// ... and so on
}
}
}
}
Now this code does NOT scale very well, and now I have duplicate code, that somewhat does the same damn thing.
I'm not entirely sure, what the best ways to solve this issue is. I have a few ideas, where I could put them in one class, either a dedicated ViewModel class, a Factory or something similar, but I don't feel that it's right.
I look forward to reading how you guys solve this.
BTW, I know this isn't very great design, but my time was limited, so I didn't refactor too much of the code.
I SHOULD NOTE That the code has to scale, so it later can be added to a database, and be translated.