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

查看:113
本文介绍了在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直接进入脚本标签中的观点,然后它的工作?这意味着必须把code页面中所有的时间,而不是加载外部脚本文件是这样的:

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?

推荐答案

有没有办法实现MVC /剃刀code的JS文件。

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

你应该在你的HTML设置可变数据(在.cshtml文件),这是概念上确定,不违反关注(服务器生成的HTML与客户端脚本code)分离,因为如果你仔细想想它,这些变量的值是服务器问题。

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.

看看这(部分,但漂亮的)解决方法:<一href=\"http://stackoverflow.com/questions/1045451/using-inline-c-inside-javascript-file-in-mvc-framework/1045493#1045493\">Using在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天全站免登陆