Pismotality
Pismotality

Reputation: 2289

How to save string value of enum mvc

I am new to MVC. I am using the following enum in my Orders table:

public enum OrderStatus
    {
        Pending = 1,
        Held = 2,
        [Display(Name = "In Process")]
        In_Process = 3,
        Completed = 4,
        Shipped = 5,
        Returned = 6,
        Cancelled = 7
    }

and in the model:

public class Order
    {
        ...
        public OrderStatus OrderStatus { get; set; }
    {

in the view:

                <div class="form-group">
                    @Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EnumDropDownListFor(model => model.OrderStatus,
                              "--Select--", 
                              new { @class = "form-control ingUOM" })  
                            @Html.ValidationMessageFor(model => model.OrderStatus, "", new { @class = "text-danger" })
                     </div>
                 </div>

in the controller:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(OrderViewModel ovm, int id)
...

 Order order = db.Orders.FirstOrDefault(o => ((o.OrderId == id)));

                order.OrderStatus = ovm.OrderStatus;

My issue is that I want to save the string value of the enum, instead of its integer value. This is so it will be easier to display the string value of the enum in reports and other views. I have been researching this but have been unsuccessful in finding a technique to use. Any help will be much appreciated.

Upvotes: 2

Views: 1920

Answers (1)

Karel Tamayo
Karel Tamayo

Reputation: 3760

You could use a helper class to try to get the value of the Display attribute if it exists for the enum member and fallback to call ToString() if it's not found. Something like this should do the trick:

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

...

public static class DisplayAttributeHelper
{
    public static string ReadDisplay(Enum target)
    {
        var attrs = target.GetType().GetMember(target.ToString())
            .First()
            .GetCustomAttributes(typeof(DisplayAttribute), false)
            .Cast<DisplayAttribute>();

        foreach (var attr in attrs)
            return attr.GetName();

        return target.ToString();
    }
}

Now you can keep storing your enum value normally using EF or linq and when you need to show the string value call the helper class.

For instance to show that in a report you could create your report model:

public class ReportModel
{
        public OrderStatus OrderStatus { get; set; }

        public string OrderStatusDisplayText => DisplayAttributeHelper.ReadDisplay(OrderStatus);
}

Hope this helps!

Upvotes: 1

Related Questions