I took a mixture from several people's answers and wrote this HtmlHelper extension method:
public static HtmlString GetEnums<T>(this HtmlHelper helper) where T : struct
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("<script type="text/javascript">");
sb.AppendLine("if(!window.Enum) Enum = {};");
var enumeration = Activator.CreateInstance(typeof(T));
var enums = typeof(T).GetFields().ToDictionary(x => x.Name, x => x.GetValue(enumeration));
sb.AppendLine("Enum." + typeof(T).Name + " = " + System.Web.Helpers.Json.Encode(enums) + " ;");
sb.AppendLine("</script>");
return new HtmlString(sb.ToString());
}
You can then call the method using Razor syntax like this:
@(Html.GetEnums<Common.Enums.DecisionStatusEnum>())
It will then spit out javascript like this:
<script type="text/javascript">
if(!window.Enum) Enum = {};
Enum.WorkflowStatus = {"value__":0,"DataEntry":1,"SystemDecisionMade":2,"FinalDecisionMade":3,"ContractCreated":4,"Complete":5} ;
</script>
You can then use this in javascript like such:
if(value == Enum.DecisionStatusEnum.Complete)
Because of the check for property at the top (if(!window.Enum)
), this allows you to call it for multiple enums and it won't overwrite the global Enum
variable, just appends to it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…