1

Theoretical question here.

I have a property "Status" that can only accept 2 different values (open, closed) which i want to set as an enum type of property. in a codefirst mvc application, should the enum be defined in the data model, in the viewmodel or both?

I am leaning towards making the enum part of the viewmodel and the codefirst property for this model would just store the string value of the enum. Then, i would just map the 2 values back and forth using automapper. The enum property of the viewmodel would be displayed as a radiobutton.

Thoughts?

2 Answers 2

1

It depends.

1) If You have other code that can access Your data model (apart from Your views) than You probably want this Status property to be of enum type. So that this third party code will not break Your logic. Anyway, even if You don't have such code right now I suggest You to use enum for forward compatibility: mabby You or other developer will add it in the future. It's a best practice. IMHO, this is mandatory.

2) What about using enum in the view model? IMHO, this is optional. Because if You want to validate Your input You probably will do it on the server in Your controller action method. If You use radiobuttons than You even don't need to validate the input in controller. Just use this in Your view:

@model path.YourViewModel
@using YourEnumNamespace;  /* where You defined Your Status enum */

@using (Html.BeginForm("YourMethod", "YourController", FormMethod.Post, null))
{
<fieldset>
    <div>
        @foreach (var enumValue in Enum.GetValues(typeof(Status)))
        {
            <div>
                @Html.Label(enumValue.ToString())
                @Html.RadioButtonFor(model => model.Title, enumValue)
            </div>
        }
    </div>
    <input type="submit" value="Save"/>
</fieldset>
}

Just enumerate enum values as in the above code.

To summarize: there is no need to use enum type in viewmodel, but it is a good practice to think about forward compatibility and use enum type in datamodel.

Sign up to request clarification or add additional context in comments.

Comments

0

I usually have them in both my domain models and ViewModels, Entity Framework will map them to integers in the database. I created some html helpers which create drop down lists for an enum in my ViewModel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.