robin
robin

Reputation: 497

Using JsonConverter for enum element value

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

Upvotes: 1

Views: 1080

Answers (3)

Rune Grimstad
Rune Grimstad

Reputation: 36300

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();

Upvotes: 1

Stephen Reindl
Stephen Reindl

Reputation: 5819

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.

Upvotes: 1

Cameron
Cameron

Reputation: 2594

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();

Upvotes: 1

Related Questions