1

After reading this post JSON serialization of enum as string I'm still searching for a quick way to use into Razor javascript this type of Enum:

    [JsonConverter(typeof(StringEnumConverter))]
    public enum StatusReplacement
    {
        ApprovalPending = 1,
        Canceled = 2,
        Approved = 3,
        AwaitingDelivery = 4,
        Delivered = 5,
        Completed = 6
    }

By using JsonConverter I just can take the element enums but not their values. I also tried unsuccessfully to set over each element [EnumMember(Value = "")].

Expected result

...Razor...
<script>
var elementValue = @StatusReplacement.ApprovalPending;
alert(elementValue) //Expecting to return 1 instead of ApprovalPending *undefined.
</script>

I'm not sure yet if I really have use any king of html helper for this purpose. I suspicious there is an easier way to achieve it today working with MVC 4+.

Regards, Rubens

Community
  • 1
  • 1

3 Answers3

1

There's a couple of things you can do.

var elementValue = @Json.Encode(StatusReplacement.ApprovalPending);

There will be a little more overhead to doing Json.Encode however, if you you're using custom values (e.g. changing the Json value of ApprovalPending to be foo) then this is your best option.

Or, if you don't plan on doing custom values, you can just do ToString()

var elementValue = @StatusReplacement.ApprovalPending.ToString();
Cameron
  • 2,574
  • 22
  • 37
  • Great approach @cameron specially cus you considered the possibility to change enum element members descriptions. Your contribution was very useful. Thank you. – Rubens Mussi Cury Nov 10 '16 at 21:47
1

The JSON formatter takes preference on the output of the data and provides a string output of the enum value itself:

var data = "@StatusReplacement.ApprovalPending"; // = ApprovalPending

You should use

var data = @((int)StatusReplacement.ApprovalPending); // = 1

to explicitly use the int value.

Stephen Reindl
  • 5,659
  • 2
  • 34
  • 38
1

The easiest solution is probably to just cast your enum value into an int in your Razor code:

var elementValue = @((int)StatusReplacement.ApprovalPending);

It's a bit clumsy but does the work. Alternatively you could add an extension method that returns the int value:

Add the following method to a static class:

public static int EnumValue(this StatusReplacement statusReplacement) 
{
   return (int)statusReplacement;
}

This can then be called from your razor code:

var elementValue = @StatusReplacement.ApprovalPending.EnumValue();
Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76
  • You are right @rune-grimstad I guess the easiest solution is cast enum. However, the other solutions you've suggested are very welcome and also easy to use. Thank you. – Rubens Mussi Cury Nov 10 '16 at 22:01