gpt4 book ai didi

javascript - 在 JS 文件中访问 ViewModel (asp.net MVC)

转载 作者:搜寻专家 更新时间:2023-11-01 04:36:57 25 4
gpt4 key购买 nike

我一直在 Razor 中使用类似的东西

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


</script>

}

但这看起来不太干净,因为它与布局位于同一文件中(因为它不能直接从 .js 文件运行)。除了访问和查看在 .js 文件中传递的 ViewModel,还有什么干净的替代方法?

最佳答案

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

一些 .js 文件

function Common() {
var _this = this;

this.viewModel = null;

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

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

然后在加载 View 时传递 ViewModel

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

关于javascript - 在 JS 文件中访问 ViewModel (asp.net MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23665597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com