Access a Model property in a javascript file?

后端 未结 7 1432
醉梦人生
醉梦人生 2020-12-17 14:22

Is it possible to access a Model property in an external Javascript file?

e.g. In \"somescript.js\" file

var currency = \'@Model.Currency\';
alert(cu         


        
7条回答
  •  暖寄归人
    2020-12-17 15:08

    What i did was create a js object using the Method Invocation pattern, then you can call it from the external js file. As js uses global variables, i encapsulate it to ensure no conflicts from other js libraries. Example: In the view

     @section scripts{
            
            @Scripts.Render("~/Scripts/PathToExternalScriptFile.js")   
        }
    

    Now inside of the external page you can then get the data with a protected scope to ensure that it does not conflict with other global variables in js.

      console.log('VariableOne = ' + thisPage.variableOne);
      console.log('Some URL = ' + thisPage.someAjaxUrl());
    

    Also you can wrap it inside of a Module in the external file to even make it more clash proof. Example:

    $(function () {
        MyHelperModule.init(thisPage || {});
    });
    
    var MyHelperModule = (function () {
        var _helperName = 'MyHelperModule';
    
        // default values
        var _settings = { debug: false, timeout:10000, intervalRate:60000};    
    
        //initialize the module
        var _init = function (settings) {
    
            // combine/replace with (thisPage/settings) passed in
            _settings = $.extend(_settings, settings);
    
            // will only display if thisPage has a debug var set to true            
            _write('*** DEBUGGER ENABLED ***');             
    
            // do some setup stuff              
    
            // Example to set up interval
            setInterval(
                function () { _someCheck(); }
                , _settings.intervalRate
            );
            return this; // allow for chaining of calls to helper  
        };
    
        // sends info to console for module
        var _write = function (text, always) {
            if (always !== undefined && always === true || _settings.debug === true) {
                console.log(moment(new Date()).format() + ' ~ ' + _helperName + ': ' + text);
            }
        };
    
        // makes the request 
        var _someCheck = function () { 
            // if needed values are in settings
            if (typeof _settings.someAjaxUrl === 'function' 
                && _settings.variableOne !== undefined) { 
                $.ajax({
                    dataType: 'json'
                    , url: _settings.someAjaxUrl()
                    , data: {
                        varOne: _settings.variableOne                    
                    }
                    , timeout: _settings.timeout
                }).done(function (data) {
                    // do stuff
                    _write('Done');
                }).fail(function (jqxhr, textStatus, error) {                
                    _write('Fail: [' + jqxhr.status + ']', true);
                }).always(function () {
                    _write('Always');
                });             
            } else {// if any of the page settings don't exist
                _write('The module settings do not hold all required variables....', true);            
            }
        };
    
        // Public calls
        return {
            init: _init
        }; 
    
      })();
    

提交回复
热议问题