Julian Wilson
Julian Wilson

Reputation: 2470

Entity Framework ASP.NET MVC Data Annotations Custom Formatting

I'm trying to make a more customized data annotation for one of attributes. In my data model, I have an attribute:

public int AutoCallableStart { get; set; }

And I want to display it like this: 1 --> "1st" 2 --> "2nd" 3 --> "3rd", ..., etc.

In a view model implementation (my current implementation), I have:

public string CallFrom
    {
        get
        {
            switch (_callableIncome.AutoCallableStart)
            {
                case 1:
                    return "1st";
                case 2:
                    return "2nd";
                case 3:
                    return "3rd";
                case 4:
                    return "4th";
                case 5:
                    return "5th";
                default:
                    return "???";
            }

        }
    }

Can this be done using data annotations such as something like

[Display(Name="CallFrom")
[TypeConverter(Type=".....")]

using a TypeConverter? I've googled everywhere but can't find anything. I want to take full advantage of EF and scrap my view models.

Thanks for your help.

Upvotes: 0

Views: 216

Answers (1)

Julian Wilson
Julian Wilson

Reputation: 2470

Based on the comments, I've decided to make a DisplayTemplate. I've also kept the view models. Here's my display template: \Shared\DisplayTemplates\CallFrom.cshtml

@model int

@{
switch (@Model)
{
    case 1:
        <span>1st</span>
        break;
    case 2:
        <span>2nd</span>
        break;
    case 3:
        <span>3rd</span>
        break;
    case 4:
        <span>4th</span>
        break;
    case 5:
        <span>5th</span>
        break;
    default:
        <span>???</span>
        break;
}
}

And my annotation in my VIEW MODEL

[Display(Name="CallFrom")]
[UIHint("CallFrom")]
public int AutoCallableStart
{
    get { return _callableIncome.AutoCallableStart; }
}

Works like a charm!

Upvotes: 1

Related Questions