Access a Model property in a javascript file?

后端 未结 7 1425
醉梦人生
醉梦人生 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:09

    I tackled this problem using data attributes, along with jQuery. It makes for very readable code, and without the need of partial views or running static javascript through a ViewEngine. The JavaScript file is entirely static and will be cached normally.

    Index.cshtml:

    @model Namespace.ViewModels.HomeIndexViewModel
    

    Index

    @section scripts { }

    Index.js:

    jQuery(document).ready(function ($) {
        // import all the variables from the model
        var $vars = $('#Index\\.js').data();
    
        alert($vars.page);
        alert($vars.actionUrl); // Note: hyphenated names become camelCased
    });
    

    _Layout.cshtml (optional, but good habit):

    
        
    
        @Scripts.Render("~/bundles/js")
        @RenderSection("scripts", required: false)
    
    

提交回复
热议问题