Search code examples
javascriptasp.net-mvcknockout.jsrequirejsviewbag

Pass ViewBag data to requirejs or knockout


I'm new to js and now trying to integrate HTML5 AJAX File Uploader Module into my ASP.NET MVC project.

In my project, there's a ViewBag.UserID, and in the view I use the script from the module:

<script type="text/javascript" data-main="/scripts/main" src="/Scripts/require.js"></script>

I suppose I can pass UserID to main.js using the script above, so that I can use something like

var UserID;

html5Upload.initialize({
    // URL that handles uploaded files
    uploadUrl: '/file/upload?Userid=' + UserID,

    ...
    });

But... how can I do to fulfill that?


Solution

  • You could have some bootstrapping code to integrate server-side globals into your javascript. E.g.:

    <script>
    (function(myNamespace) {
      "use strict";
    
      myNamespace.UserInfo = {
        UserID: '@ViewBag.UserID' // injects viewbag info into javascript
      };
    
    }(window.myNamespace = window.myNamespace || {}));
    </script>
    

    Now any bit of javascript you have can access the global myNamespace variable's UserInfo property, which contains the viewbag data. For example:

    uploadUrl: '/file/upload?Userid=' + myNamespace.UserInfo.UserID,