0

I have a bunch of javascript inside my view and its getting quite large so I want to move it to a separate js file. The one issue I have is that I have this line:

 var tags = <%= new JavaScriptSerializer().Serialize(Model.Tags) %>;

which I obviously can't just copy over since it has the server side asp.net-mvc tags. What is the recommended way to deal with that:

  1. Keep this one function inside the aspx page and have the javascript from the seperate js file call that function?

  2. Other??

3 Answers 3

1

What you could do is have a JavaScript object contain all the information you get from the controller and pass it through a javascript function which is located in the external javascript file. You can also pass other information through the options variable.

Example:

 var options = {
    tags: <%= new JavaScriptSerializer().Serialize(Model.Tags) %>
 };
 initPage(options);

Usage:

function initPage(options) {
    console.log(options.tags);
}
Sign up to request clarification or add additional context in comments.

Comments

0

This depends a lot on the way you want to use it and the level of repeating.

Some thoughts:

  1. The tags are static. Then I guess then don't really need to be in the model. So you can move them into a new Controller action which outputs the scipt. You can call this action in the <script> part of your view.
  2. The tags are changing very frequently (maybe even at every page load). Then there is no gain in moving this in a separate script file.

Comments

0

If you set up your javascript file with proper closures, you can expose a property (or better yet, a parameter to the object/method) with which to pass that information along when you call that function.

Your Javascript would need to be something like this:

var JsFile = (function() {
    var tags;
    // list all of your methods here.

    return {
        var setTags = function(_tags) {
            tags = _tags;
        }
    };
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.