Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Share enums between C# and Javascript in MVC Razor

I have seen this useful answer to a question for adding constants into a javascript file so it can be used with razor views: Share constants between C# and Javascript in MVC Razor

I'd like to be able to do the same except define enums, but I'm not sure how to convert the C# Enum into a constant in javascript.

Off GetType(), there doesn't seem to be a way of actually getting at the constant value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...