简体   繁体   English

在C#/ Razor中使用JavaScript的最佳(或正确)方法?

[英]Best (or correct) way to use JavaScript with C#/Razor?

What is the best and maybe correct way of mising JavaScript code with Razor? 用Razor混淆JavaScript代码的最好甚至正确的方法是什么? At the moment i put my JavaScript code in an external JavaScript file "external.js" but there i have the problem that i can not access the C# variables of my model directly (i can do it, but it makes the whole thing a little bit complicated). 目前,我将JavaScript代码放在外部JavaScript文件“ external.js”中,但存在一个问题,即我无法直接访问模型的C#变量(我可以做到,但这会使整个过程变得有些困难有点复杂)。 This only works with Razor-Syntax @Model.Variable when i embed my JavaScript Code inside the view in the -Section/Tags. 当我将我的JavaScript代码嵌入到-Section / Tags中的视图内时,这仅适用于Razor-Syntax @ Model.Variable。

So i thought about this situation and don't find an answer. 所以我考虑了这种情况,没有找到答案。 I read and thought it would be the best to put all JavaScript code in one file, so that the browser loads the whole stuff only one time and then read out of the cache (Performance). 我阅读并认为最好将所有JavaScript代码放在一个文件中,以便浏览器仅加载一次整个内容,然后从缓存中读取(性能)。 But could it be better to write the JavaScript code inside each View instead of putting into one huge file? 但是,将JavaScript代码写入每个View而不是放入一个大文件会更好吗?

Putting your Javascript directly into your view isn't going to affect the load of your page in any significant manner (unless your Javascript really is a behemoth). 直接将Javascript放入视图不会以任何重要方式影响页面的负载(除非Javascript确实是庞然大物)。

It will be transported (and subsequently cached) when the view is requested. 请求视图时将传输(并随后将其缓存)。

If you're wanting to use your razor variables directly in Javascript, then having it in the view is your most sensible option 如果您想直接在Javascript中使用剃刀变量,那么将其显示在视图中是您最明智的选择

That is, of course, the view is intended to be used as a partial - in which case you probably want to rethink the design 也就是说,当然,该视图仅用作局部视图-在这种情况下,您可能需要重新考虑设计

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM