如何在 .js 文件中嵌入 Razor C# 代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9406648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:14:59  来源:igfitidea点击:

How to embed Razor C# code in a .js file?

c#javascriptasp.net-mvc-3razor

提问by Kenet Jervet

Have to embed javascript code block with

必须嵌入 javascript 代码块

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

But Razor code won't compile in a .jsfile, included from a .cshtmlfile.

但是 Razor 代码不会在.js文件中编译,包括在.cshtml文件中。

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

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

Thank you.

谢谢你。

采纳答案by jcreamer898

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

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

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

不一定是最好的选择,但如果你必须这样做,它会做...

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

您可以尝试的另一件事是在 html 元素上使用数据属性,例如 jQuery.validate.unobtrusive 的作用...

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

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

回答by Kenet Jervet

You can't. Nor should you even try. Keep them separate. This goes for the other way around, but you should look into Unobtrusive JavaScript. That design pattern applied throughout the project is a great idea.

你不能。你也不应该尝试。将它们分开。这正好相反,但您应该研究Unobtrusive JavaScript。在整个项目中应用的设计模式是一个好主意。

回答by René

While I agree that you should think twice about using Razor inside your Javascript files, there is a Nuget package that can help you. It's called RazorJS.

虽然我同意您在 Javascript 文件中使用 Razor 时应该三思而后行,但有一个 Nuget 包可以帮助您。它被称为RazorJS

The author of the package has a blog postabout it, that explains how to use it.

该包的作者有一篇关于它的博客文章,解释了如何使用它。

回答by R. Schreurs

Maybe I can provide a useful work-around, depending on what you wish to accomplish.

也许我可以提供有用的解决方法,具体取决于您希望完成的工作。

I was tempted to find a way to evaluate razor expressions in a java script file. I wanted to attach a jQuery click event handler to submits with a specific class that are found on many pages. This should be done in a jQuery document ready event handler. This click event would perform an ajax call.

我很想找到一种方法来评估 java 脚本文件中的 razor 表达式。我想附加一个 jQuery 单击事件处理程序,以使用在许多页面上找到的特定类进行提交。这应该在 jQuery 文档就绪事件处理程序中完成。此单击事件将执行 ajax 调用。

The url of these should be application relative, not absolute, in case the application lives below the root level. So, I wanted to use something like

这些 url 应该是应用程序相对的,而不是绝对的,以防应用程序位于根级别以下。所以,我想使用类似的东西

$(document).ready(function () {
    $('input[type="submit"].checkit)').click(function (e) {
        $.ajax({
            type: 'POST',
            url: '@Url.Content("~/checkit")', //Razor expression here
            dataType: 'json',
            success: function (data) {
                if (!data) {
                    e.preventDefault();
                    handleResponse(data);
                }
            },
            data: null,
            async: false
        });
    });
});

I solved this by wrapping the code in a function Checkit and moving the call to the layout view:

我通过将代码包装在函数 Checkit 中并将调用移动到布局视图来解决这个问题:

        $(document).ready(function () {
            Checkit('@Url.Content("~/checkit")');
        });

Most of the javascript code is still in a javascript file.

大多数 javascript 代码仍然在一个 javascript 文件中。

回答by scradam

Here's a sample Razor webpage (not an MVC view, although that would be similar) that will serve Javascript. Of course, it's atypical to dynamically write Javascript files, but here's a sample nonetheless. I used this once in a case where I wished to provide JSON data and some other stuff that was expensive to compute and changed rarely - so the browser could include it and cache it like a regular JS file. The trick here is just to set the Response.ContentTypeand then use something like the Razor <text>tags for your Javascript.

这是一个将提供 Javascript 的示例 Razor 网页(不是 MVC 视图,尽管这很相似)。当然,动态编写 Javascript 文件是不典型的,但这里有一个示例。在我希望提供 JSON 数据和其他一些计算成本高且很少更改的东西的情况下,我曾经使用过它 - 因此浏览器可以包含它并像常规 JS 文件一样缓存它。这里的技巧只是设置Response.ContentType然后<text>为您的 Javascript使用类似 Razor标签的东西。

@{
Response.ContentType = "text/javascript";
Response.Cache.SetLastModified(System.Diagnostics.Process.GetCurrentProcess().StartTime);
Response.Cache.SetExpires(System.DateTime.Now.Date.AddHours(28));
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
<text>
var someJavaScriptData = @someSortOfObjectConvertedToJSON;
function something(whatever){
}
</text>
}

You could then include it as so in your other Razor file:

然后,您可以将其包含在其他 Razor 文件中:

<script src="MyRazorJavascriptFile.cshtml"></script>

回答by clement

And what about including a .cshtml that only contains js?

包含一个只包含 js 的 .cshtml 怎么样?

.csthml parent

.csthml 父级

@RenderPage("_scripts.cshtml")

_scripts.cshtml that contains js

_scripts.cshtml 包含 js

<script type="text/javascript">
alert('@Datetime.ToString()');
</script>