简体   繁体   English

混合 Razor 和 Javascript 代码

[英]Mix Razor and Javascript code

I'm pretty confused with how to mix razor and js.我对如何混合 razor 和 js 感到很困惑。 This is the current function I am stuck with:这是我坚持使用的当前功能:

<script type="text/javascript">

        var data = [];

        @foreach (var r in Model.rows)
        {
                data.push([ @r.UnixTime * 1000, @r.Value ]);
        }

If I could declare c# code with <c#></c#> and everything else was JS code -- this would be what I am after:如果我可以用<c#></c#>声明 c# 代码,而其他一切都是 JS 代码——这就是我所追求的:

<script type="text/javascript">

        var data = [];

        <c#>@foreach (var r in Model.rows) {</c#>
                data.push([ <c#>@r.UnixTime</c#> * 1000, <c#>@r.Value</c#> ]);
        <c#>}</c#>

What is the best method to achieve this?实现这一目标的最佳方法是什么?

Use <text> :使用<text>

<script type="text/javascript">

   var data = [];

   @foreach (var r in Model.rows)
   {
      <text>
            data.push([ @r.UnixTime * 1000, @r.Value ]);
      </text>
   }
</script>

Inside a code block (eg, @foreach ), you need to mark the markup (or, in this case, Javascript) with @: or the <text> tag .在代码块(例如@foreach )中,您需要使用@:<text>标记来标记标记(或在本例中为 Javascript)。

Inside the markup contexts, you need to surround code with code blocks ( @{ ... } or @if , ...)在标记上下文中,您需要用代码块( @{ ... }@if , ...)包围代码

you also can simply use你也可以简单地使用

<script type="text/javascript">

   var data = [];

   @foreach (var r in Model.rows)
   {
       @:data.push([ @r.UnixTime * 1000, @r.Value ]);
   }
</script>

note @:注意@:

Never ever mix more languages.永远不要混合更多的语言。

<script type="text/javascript">
    var data = @Json.Encode(Model); // !!!! export data !!!!

    for(var prop in data){
      console.log( prop + " "+ data[prop]);
    }

In case of problem you can also try如果有问题,您也可以尝试

@Html.Raw(Json.Encode(Model));

A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.一种将 javascript 与视图分离但仍使用 razor 的非常规方法是制作一个Scripts.cshtml文件并将混合的 javascript/razor 放在那里。

Index.cshtml索引.cshtml

<div id="Result">
</div>

<button id="btnLoad">Click me</button>

@section scripts
{
    @Html.Partial("Scripts")
}

Scripts.cshtml脚本.cshtml

<script type="text/javascript">
    var url = "@Url.Action("Index", "Home")";

    $(document).ready(function() {
        $("#btnLoad").click(function() {
            $.ajax({
                type: "POST",
                url: url ,
                data: {someParameter: "some value"},
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
        });
    });
</script>

您可以将<text>标记用于带有 javascript 的两个 cshtml 代码

This is my way to hack Razor and use Javascript without freaking out Intellisense.这是我破解 Razor 并使用 Javascript 而不会吓坏 Intellisense 的方法。

Obviously you should use <text> but with an "expedient": double braces before.显然你应该使用<text>但有一个“权宜之计”:之前的双大括号。

This is what happens if a single brace is used:如果使用单个大括号会发生以下情况:

在此处输入图片说明

This is what happen if a couple of braces are used:如果使用几个大括号,会发生这种情况:

在此处输入图片说明

Now constants and variable have been recognized.现在常量和变量已经被识别。 It's better, but not good!它更好,但不是很好! There is still the "less than" symbol that confuses intellisense making it think that following is the name of a tag.仍然存在混淆智能感知的“小于”符号,使其认为以下是标签的名称。 The "less than" sign is signaled as error and from here there are parsing errors as "console.log" shows. “小于”符号表示为错误,从这里开始有解析错误,如“console.log”所示。 You need to add something that quiets intellisense and doesn't get returned in the final JS code at compile time.您需要添加一些使智能感知安静并且在编译时不会在最终 JS 代码中返回的内容。

Solution: use this comment after "less than": /*>*/解决方法:在“小于”之后使用此注释: /*>*/

This is the result这是结果

在此处输入图片说明

It's quite strange to see, but it works as it should.看起来很奇怪,但它应该可以正常工作。

Wrap your Razor code in @{ } when inside JS script and be aware of using just @ Sometimes it doesn't work:在 JS 脚本中将 Razor 代码包裹在 @{} 中,并注意仅使用 @ 有时它不起作用:

function hideSurveyReminder() {
       @Session["_isSurveyPassed"] = true;
    }

This will produce这将产生

function hideSurveyReminder() {
       False = true;
    }

in browser =(在浏览器中 =(

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

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