在JS文件中访问ViewModel(asp.net MVC) [英] Accessing ViewModel in JS file (asp.net MVC)

查看:76
本文介绍了在JS文件中访问ViewModel(asp.net MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Razor里面一直使用这样的东西

I have been using something like this inside Razor

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


      </script>

}

但这看起来并不那么干净,因为它也是一样的file作为布局,(因为它不能直接从.js文件中工作)。
访问和查看在.js文件中传递的ViewModel的任何干净的替代方法?

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?

推荐答案

您无法直接访问.js文件中的ViewModel,因为它是Web服务器上的静态文件。但是有一种解决方法,你可以使用参数将ViewModel传递给.js文件。

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

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();
});

然后只在View加载时传递ViewModel

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

这篇关于在JS文件中访问ViewModel(asp.net MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆