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

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

问题描述

必须嵌入 javascript 代码块

Have to embed javascript code block with

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

但是 Razor 代码不会在 .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?

谢谢.

推荐答案

当我遇到这个问题时,有时我会在 .cshtml 文件中可以访问的 .js 文件中提供一个函数...

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" />

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

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