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
419 views
in Technique[技术] by (71.8m points)

c# - Working example for JavaScriptResult in asp.net mvc

Can somebody provide a working example of JavaScriptResult in asp.net mvc. I understand that it returns javascript which is then executed on the client side and also that the content type of the response is set to text/javascript. I need some working example to see this thing in action.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Note: This answer was written in 2011 and looking at it nowadays, it's more of a hack. It's better to load values through AJAX request that hits a JSON endpoint API.

Here's a practical case: I have a GlobalSettings static C# class that contains static Properties of values that are used through the whole system in the ASP.NET MVC backend side of things.

Some of those values need to be shared with JS code. So I created an Action that returns JavaScriptResult which basically pumps out those values into global JS variables.

Note: Change the output cache period to suit your needs

[OutputCache(Duration = 999999)]
public virtual JavaScriptResult Global()
{
        var script = $@"
            MaxNotificaitonsToShow = {GlobalSettings.MaxNotificaitonsToShow};
            ItemsPerPage = {GlobalSettings.ItemsPerPage};
        ";
    return JavaScript(script);
}

And then I load the response of this action as a JS file inside all pages through the HTML footer:

<script type="text/javascript" src="/JS/Global"></script>

Now I can get the values in any Javascript file:

if(ItemsPerPage == 25)
{
   alert('it works!');
}

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

...