访问 javascript 文件中的模型属性? [英] Access a Model property in a javascript file?

查看:18
本文介绍了访问 javascript 文件中的模型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问外部 Javascript 文件中的模型属性?

Is it possible to access a Model property in an external Javascript file?

例如在somescript.js"文件中

e.g. In "somescript.js" file

var currency = '@Model.Currency';
alert(currency);

在我的视图中

<script src="../../Scripts/somescript.js" type="text/javascript">

这似乎不起作用,但是如果我将 javascript 直接放入脚本标签内的视图中,那么它是否起作用?这意味着必须一直将代码放在页面中,而不是像这样加载外部脚本文件:

This doesn't appear to work, however if I put the javascript directly into the view inside script tags then it does work? This means having to put the code in the page all the time instead of loading the external script file like this:

@model MyModel;

<script lang=, type=>
var currency = '@Model.Currency';
alert(currency);
</script>

有什么办法可以解决这个问题吗?

Is there any way around this?

推荐答案

没有办法在JS文件中实现MVC/Razor代码.

There is no way to implement MVC / Razor code in JS files.

您应该在 HTML 中(在 .cshtml 文件中)设置变量数据,这在概念上是可以的,并且不会违反关注点分离(服务器生成的 HTML 与客户端脚本代码),因为如果您考虑一下,这些变量值是一个服务器问题.

You should set variable data in your HTML (in the .cshtml files), and this is conceptually OK and does not violate separation of concerns (Server-generated HTML vs. client script code) because if you think about it, these variable values are a server concern.

看看这个(部分但很好的)解决方法:在 MVC 框架中的 Javascript 文件中使用内联 C#

Take a look at this (partial but nice) workaround: Using Inline C# inside Javascript File in MVC Framework

这篇关于访问 javascript 文件中的模型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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