Accessing ViewModel in JS file (asp.net MVC

2019-04-29 17:06发布

问题:

I have been using something like this inside Razor

@section Includes {  
      <script type="text/javascript">
        var somestuffneeded = @(Html.Raw(Json.Encode(Model.datamember))); 


      </script>

}

But this looks not so clean because it goes in the same file as the layout, (since it won't work from the .js file directly). Any clean alternatives to accessing and viewing the ViewModel passed inside .js file?

回答1:

You can't directly access ViewModel in .js file because its static file on your web server. But there is a workaround that you can pass ViewModel to .js file with parameter.

some .js File

function Common() {
    var _this = this;

    this.viewModel = null;

    this.showViewModel = function () {
       alert(_this.viewModel);
    };
}

var common = null;
$().ready(function () {
    common = new Common();
});

then just pass ViewModel when View is Loaded

@section Includes {  
  <script type="text/javascript">
    var somestuffneeded = @(Html.Raw(Json.Encode(Model.datamember))); 
    $(document).ready(function () {
          common.viewModel = somestuffneeded;
          common.showViewModel();
    });
  </script>
}