如何嵌入剃刀C#代码.js文件? [英] How to embed Razor C# code in a .js file?

查看:192
本文介绍了如何嵌入剃刀C#代码.js文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有嵌入用

<script type='text/javascript'>
  ...
</script>



但剃刀代码将不能在的.js 文件,从 .cshtml 文件包括在内。

But Razor code won't compile in a .js file, included from a .cshtml file.

如何使这项工作?或有任何其他优雅的方式来产生类似的效果?

How to make this work? Or is there any other elegant way to have a similar effect?

感谢您。

推荐答案

当我面对这个问题,有时我会提供在.js文件中的函数是在.cshtml文件访问...

When I face this problem sometimes I will provide a function in the .js file that is accessible in the .cshtml file...

// someFile.js
var myFunction = function(options){
    // do stuff with options
};

// razorFile.cshtml
<script>
    window.myFunction = new myFunction(@model.Stuff);
    // If you need a whole model serialized then use...
    window.myFunction = new myFunction(@Html.Raw(Json.Encode(model)));
</script>



不一定是最好的选择,但如果你要做到这一点,它会做...

Not necessarily the BEST option, but it'll do if you have to do it...

您可以也许尝试用你的HTML元素,如jQuery.validate.unobtrusive如何做数据属性的另一件事......

The other thing you could maybe try is using data attributes on your html elements like how jQuery.validate.unobtrusive does...

//someFile.js
var options = $("#stuff").data('stuff');

// razorFile.cshtml
<input type="hidden" id="stuff" data-stuff="@model.Stuff" />

这篇关于如何嵌入剃刀C#代码.js文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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