Accessing ViewModel in JS file (asp.net MVC)

ε祈祈猫儿з 提交于 2019-12-07 04:20:16

问题


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>
}


来源:https://stackoverflow.com/questions/23665597/accessing-viewmodel-in-js-file-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!